需要JSON数据才能使用foreach显示多个数组

时间:2014-09-17 06:10:02

标签: php json foreach

我正在尝试显示我为每个循环使用PHP创建的JSON数据的信息。我遇到了多维数组的问题。我无法一次性选择它们,当有30个时我不希望每个循环都有30个。

这是我的Json数据:

[
{
    "country": "us",
    "city_ascii": "destin",
    "city": "Destin",
    "region": "FL",
    "population": "12115",
    "latitude": "30.393333",
    "longitude": "-86.495833"
},
{
    "country": "us",
    "city_ascii": "destino",
    "city": "Destino",
    "region": "PR",
    "population": "0",
    "latitude": "18.130278",
    "longitude": "-65.436667"
}
]

这是我用于处理JSON的PHP:

$json = json_encode($rows,JSON_PRETTY_PRINT);

$data = json_decode($json);


foreach($data[0] as $key => $value) {
    if($key == 'city_ascii' || $key == 'latitude' || $key == 'longitude') {

    } else{
        echo $key.' '.$value.'<br>';
    }
}

你可以看到我选择了$ data [0],实际上我希望在这个foreach循环中从JSON显示每个数组。我希望我能彻底解释自己。任何帮助,将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

您不需要多个循环。你所需要的只是

foreach($data as $location)
{
  echo $location->city;  // or country or whatever
}

<强> Fiddle

答案 1 :(得分:1)

将json数据解析为数组,并在true中传递json_decode参数并迭代所有循环尝试

$str = '[
{
    "country": "us",
    "city_ascii": "destin",
    "city": "Destin",
    "region": "FL",
    "population": "12115",
    "latitude": "30.393333",
    "longitude": "-86.495833"
},
{
    "country": "us",
    "city_ascii": "destino",
    "city": "Destino",
    "region": "PR",
    "population": "0",
    "latitude": "18.130278",
    "longitude": "-65.436667"
}
]';
$json = json_decode($str, true);

foreach($json as $k=>$v) {
  foreach($v as $k1=>$v1) {
    if($k1 == 'city_ascii' || $k1 == 'latitude' || $k1 == 'longitude'){}
    else{ echo $k1.' '.$v1.'<br>';}
  }
}

会给你输出: -

country us
city Destin
region FL
population 12115
country us
city Destino
region PR
population 0