You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP接收POST JSON数据用foreach遍历多对象数组报错如何解决

问题原因梳理

  • 根级JSON结构是索引数组:sections存放在$data[0]下,questions存放在$data[1]下,直接访问$data['sections']会抛出「Undefined array key」错误
  • 关联数组键名未加引号:PHP会将未加引号的section_id识别为常量,若常量未定义就会抛出警告,无法正确读取对应值
  • 额外注意:你提供的示例JSON里有多处多余的末尾逗号(比如每个对象最后一个属性后面的逗号),不符合JSON规范,会导致json_decode解析失败返回null,实际提交时要先清理掉多余逗号。

修正后代码

// 读取输入流解析JSON
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);

// 先加解析判断,避免解析失败时报错
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON解析失败,请检查提交的JSON格式是否正确");
}

// 遍历sections
foreach ($data[0]['sections'] as $value) {
    echo $value['section_id'];
}

// 遍历questions
foreach ($data[1]['questions'] as $value) {
    echo $value['section_id'];
}

如果想要更稳妥不依赖数组的固定索引,也可以先遍历根数组识别对应键:

$sections = [];
$questions = [];
foreach ($data as $item) {
    if (isset($item['sections'])) {
        $sections = $item['sections'];
    } elseif (isset($item['questions'])) {
        $questions = $item['questions'];
    }
}

foreach ($sections as $sec) {
    echo $sec['section_id'];
}
foreach ($questions as $q) {
    echo $q['section_id'];
}

内容的提问来源于stack exchange,提问作者dasaradhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 16:36:04