PHP嵌套foreach生成JSON时itemListElement层级错位如何修复
问题解决方案
你的代码结构错位是因为子循环生成的HowToDirection数据被写入了外层$data根节点的itemListElement字段,而非对应HowToStep内部的itemListElement字段。
修改后代码
foreach ($single_google as $row) { // 先单独定义当前step的数组,保证字段顺序符合要求 $current_step = array( "@type" => "HowToStep", "url" => "https://example.com/kitchen#step1", "name" => "Prepare the surfaces", "itemListElement" => array(), "image" => [ "@type" => "ImageObject", "url" => "https://example.com/photos/1x1/photo-step1.jpg", "height" => "406", "width" => "305" ], ); $all_step_google = json_decode($row["steps"]); foreach ($all_step_google as $single_step_google) { // 直接往当前step的itemListElement里添加数据 $current_step['itemListElement'][] = array( "@type" => "HowToDirection", // 如需使用$single_step_google的实际内容替换测试文本,直接修改此处即可 "text" => "testing", ); } // 处理完子项后再把当前step加入到全局step数组中 $data['step'][] = $current_step; } // 如果需要格式化输出JSON,可添加JSON_PRETTY_PRINT参数 print_r(json_encode($data));
关键修改说明
- 先声明当前步骤的
$current_step变量,初始itemListElement为空数组,保留在image字段之前的位置,保证JSON输出的字段顺序符合要求 - 子循环内直接操作当前步骤的
itemListElement字段写入方向数据,不再写入外层$data的根节点 - 所有子项处理完成后再将当前步骤推入全局的
step数组
内容的提问来源于stack exchange,提问作者onuwa3
相关产品推荐
相关产品推荐

