在PHP中使用带有JSON的foreach

时间:2016-08-11 08:13:42

标签: php json

我有一个像这样的JSON文件:

[
{
    "set_id": "10001",
    "name": "4x4 car",
    "img_url": "https://xxx.xxx.com/img/sets-b/10001.jpg",
    "parts": [
        {
            "part_id": "1001",
            "qty": "2",
            "color_id": "0",
            "type": 1
        },
        {
            "part_id": "1002",
            "qty": "2",
            "color_id": "0",
            "type": 1
        },
        {
            "part_id": "1003",
            "qty": "2",
            "color_id": "0",
            "type": 1
        },
        {
            "part_id": "1004",
            "qty": "2",
            "color_id": "0",
            "type": 1
        }
    ]
}
    ]

我正在使用这样的PHP代码:

 while($item = array_shift($json_output))
 {
    foreach ($item as $key => $value)
    {
        echo $key.' => '.$value."\n";
    }
 }

但它返回结果:

set_id => 9398-1 descr => 4 x 4 Crawler set_img_url => https://img.rebrickable.com/img/sets-b/9398-1.jpg parts => Array

如何退回parts信息?

2 个答案:

答案 0 :(得分:1)

如果您只想要零件

foreach ($item{"parts"] as $key => $value)
{
    echo $key.' => '.$value."\n";
}

此处示例:http://sandbox.onlinephpfunctions.com 如果你想要每2级财产:

$items=json_decode($json,true);
foreach ($items as  $item) {

    foreach ($item as $key => $value)
    {
       if( is_array($value) ) { 

          foreach ($value as $subkey => $part)
          {
              foreach ($part as $partkey => $partvalue)
              {
                  echo $key .' '. $subkey . ' ['.$partkey.'] => '.$partvalue."\n";
              }
          }
       } else {

        echo $key.' => '.$value."\n";
       }
    }

}

答案 1 :(得分:0)

也许你可以使用$array_json = json_decode($json_var, true)然后$parts = $array_json["parts"];(我没有执行代码,可能有一些错误)

http://php.net/manual/en/function.json-decode.php