PHP中如何解析并获取JSON数据里的predictions字段
解决方法
你遇到的核心问题是:输出内容不是标准JSON格式(JSON要求所有键必须用双引号包裹),且response是数组类型,你之前的访问方式忽略了数组索引。以下是分步解决方案:
1. 转换非标准JSON为标准格式
如果$response是字符串类型,先通过正则给所有未加引号的键添加双引号,转换成可解析的标准JSON:
$standardJson = preg_replace('/(\w+):/', '"$1":', $response);
2. 解析JSON为PHP数据结构
使用json_decode解析,推荐解析为关联数组(第二个参数传true),更便于字段访问:
$data = json_decode($standardJson, true); // 检查解析是否成功,排查格式问题 if (json_last_error() !== JSON_ERROR_NONE) { die('JSON解析失败:' . json_last_error_msg()); }
3. 正确获取predictions及winner字段
注意response是数组,需先取第一个元素(索引[0])才能访问内部的predictions:
// 获取完整的predictions部分 $predictions = $data['response'][0]['predictions']; // 获取winner的name值 echo $predictions['winner']['name']; // 输出:SC Braga
4. 遍历response数组(多元素场景)
如果response包含多个数据项,遍历方式如下:
foreach ($data['response'] as $item) { $winnerName = $item['predictions']['winner']['name']; echo $winnerName . '<br>'; }
补充:若$response本身是PHP对象
如果$response是API请求直接返回的对象,只需补全数组索引即可正确访问:
echo $response->response[0]->predictions->winner->name;
内容的提问来源于stack exchange,提问作者Deniz Demirel
相关产品推荐
相关产品推荐

