PHP关联数组嵌套值解析异常及CSV输出问题求助
问题原因分析与解决
问题1:无法遍历data['data']['responses']
核心原因是PHP与Python的JSON解析行为、数组/对象处理逻辑存在差异:
- 若你用
json_decode()解析JSON时未传入第二个参数true,得到的是stdClass对象而非关联数组,此时不能用数组下标['data']['responses']访问,需改用对象语法->data->responses。 - 若原JSON中
responses不是数组(比如是单个对象),PHP的foreach无法遍历单个对象,会抛出Invalid argument supplied for foreach()错误。 - 需先确认
data['data']['responses']的合法性:PHP中访问不存在的数组键会返回null,对null执行foreach会报错,可通过isset($data['data']['responses'])或is_array($data['data']['responses'])提前判断。
问题2:Reference、Type字段为NULL,同层级score正常
主要是键名匹配或层级访问错误:
- PHP和Python对数组/字典键的大小写完全敏感,如果原Payload中这两个字段的键是小写(比如
reference、type),但你在PHP里用大写['Reference']、['Type']访问,就会返回null,而score因键名大小写匹配能正常提取。 - 另一种可能是层级错误:比如Python中是
response['details']['Reference'],但PHP里直接写成response['Reference'],跳过了中间层级,导致访问不存在的键返回null。 - 可通过
var_dump($response)打印单个响应项的结构,确认Reference、Type的真实键名和层级。
示例修正(匹配Python逻辑)
假设你的Python实现代码如下:
import json import csv with open('payload.json') as f: data = json.load(f) with open('output.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Reference', 'Type', 'score', 'max_score']) for resp in data['data']['responses']: writer.writerow([ resp.get('Reference'), resp.get('Type'), resp.get('score'), resp.get('max_score') ])
对应的PHP修正代码:
<?php // 解析JSON为关联数组(必须传入第二个参数true) $data = json_decode(file_get_contents('payload.json'), true); // 校验responses结构合法性 if (!isset($data['data']['responses']) || !is_array($data['data']['responses'])) { die("Invalid responses structure"); } $fp = fopen('output.csv', 'w'); // 写入CSV表头 fputcsv($fp, ['Reference', 'Type', 'score', 'max_score']); foreach ($data['data']['responses'] as $resp) { // 使用??运算符处理键不存在的情况,避免Notice级错误 $reference = $resp['Reference'] ?? null; $type = $resp['Type'] ?? null; $score = $resp['score'] ?? null; $max_score = $resp['max_score'] ?? null; fputcsv($fp, [$reference, $type, $score, $max_score]); } fclose($fp); ?>
内容的提问来源于stack exchange,提问作者Terry Brooks Jr
相关产品推荐
相关产品推荐

