阅读PHP Multi Array中的项目

时间:2015-11-13 18:37:07

标签: php arrays json

我想使用foreach在PHP中阅读以下JSON信息。我是新手,需要一些帮助。出于隐私原因,我仅提供了一小部分数据样本。

最终目标是获取服务器阵列中的所有“id”和“real_address”。

[
   {
      "id":"d87df8g7sdfg89",
      "status":false,
      "servers":[
         {
            "status":false,
            "platform":null,
            "server_id":"adsfasdfasdfasdf",
            "virt_address6":"fd00:c0a8:f800:0:192:168:248:5",
            "virt_address":"192.168.248.5",
            "name":"Private",
            "real_address":null,
            "connected_since":null,
            "id":"aasdfasdfasdfsafde",
            "device_name":null
         }
      ],
   },
   {
      "id":"asd89asd8f",
      "status":true,
      "servers":[
         {
            "status":true,
            "platform":"linux",
            "server_id":"fasdsdfasdfasdf",
            "virt_address6":"fd00:c0a8:f800:0:192:168:248:3",
            "virt_address":"192.168.248.3",
            "name":"Private",
            "real_address":"5.5.5.52",
            "connected_since":1447406908,
            "id":"asdfasdfasdfasdf",
            "device_name":"thriving-fields-2667"
         }
      ],
   }
]

3 个答案:

答案 0 :(得分:0)

您可以使用json_decode

$data = json_decode($json, true);

foreach ($data as $value) {
    foreach ($value['servers'] as $server) {
        echo $server['real_address'];
    }
}

答案 1 :(得分:0)

像这样......

$items = json_decode($json);
foreach($items as $item){
    foreach($item->servers as $server)
    {
        echo $server->server_id . " - ". $server->status;
    }
}

答案 2 :(得分:0)

如果array_column()有PHP> = 5.5.0,可以试试这个:

$array = json_decode($json, true);

foreach (array_column($array, 'servers') as $server) {   
    echo $server['real_address'];
}