首页 > 解决方案 > 使用php循环生成多级关联数组

问题描述

试图从嵌套的 php 循环中为 json 输出生成数组,关于如何完成此操作的任何建议?

这是我正在使用的当前代码

$v_id=0;
$x=0;
$item[] = array();
foreach ($abc as $vm) {
    foreach ($vm->activity as $record) {

        $item['instruction']              = $record->step;
        $item['id']              = $x;
        $id++;

    } 
    $v_id++;
}

然而,主循环语句的每个循环都高估了先前的条目

这是所需的输出

steps": [
        {
            "v_id": 0,
            "instruction_steps": [
                {
                    "id": 0,
                    "instruction": "<p>Select something &lt;/p>",
                  
                   
                {
                    "id": 1,
                    "instruction": "<p>Do something</p>",
                   
                }
            ]
        },

标签: phparrays

解决方案


你需要使用array_push()

$v_id=0;

$steps = array();

foreach ($abc as $vm) {
   $item = array();
   $item["v_id"] = $v_id;

   $instruction_steps = array();
   $x=0; // This will reset for each

    foreach ($vm->activity as $record) {
      $row = array();
      $row['id'] = $x;
      $row["instruction"] = $record->step;
      array_push($instruction_steps, $row); // push to i-steps

      $x++;

    }
    $item["instruction_steps"] = $instruction_steps;
    array_push($steps, $item); // push to steps

    $v_id++;
}

$response = array();
$response["success"] = true;
$response["steps"] = $steps;
echo json_encode($response);

推荐阅读