Php 需要JSON数据才能使用foreach显示多个数组
我试图显示使用PHP为每个循环创建的JSON数据中的信息。多维数组存在问题。我不能一次全部选择它们,当有30个循环时,我不希望每个循环都有30个循环 以下是我的Json数据:Php 需要JSON数据才能使用foreach显示多个数组,php,json,foreach,Php,Json,Foreach,我试图显示使用PHP为每个循环创建的JSON数据中的信息。多维数组存在问题。我不能一次全部选择它们,当有30个循环时,我不希望每个循环都有30个循环 以下是我的Json数据: [ { "country": "us", "city_ascii": "destin", "city": "Destin", "region": "FL", "population": "12115", "latitude": "30.393333", "longit
[
{
"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>';
}
}
$json=json\u encode($rows,json\u PRETTY\u PRINT);
$data=json_decode($json);
foreach($data[0]作为$key=>$value){
如果($key=='city|ascii'.$key=='latitude'.$key=='longitude'){
}否则{
回显$key.'.$value.'
';
}
}
如您所见,我选择了$data[0],实际上我希望在这个foreach循环中显示JSON中的每个数组。我希望我能彻底地解释我自己。任何帮助都将不胜感激
谢谢大家! 您不需要多个循环。你所需要的只是
foreach($data as $location)
{
echo $location->city; // or country or whatever
}
将json数据解码为数组,并在
json\u decode
中传递true
参数,然后迭代所有循环
$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>';}
}
}
为什么要先对数据进行编码,然后再进行解码?只要把
$rows
循环一下就行了。我想我做错了。每次使用“foreach($data as$key=>$value){}”时,我都会得到一个错误。您能解释一下原因吗?不,您不是在做foreach($data
),而是在做foreach($data[0]
),这只是该数组的第一个值。如果它没有子数组,则循环将不起作用。
country us
city Destin
region FL
population 12115
country us
city Destino
region PR
population 0