我需要获取远程更改的json代码并在php中显示数据 当用户加载页面时。 (回声)
我有这个代码: (JSON输出:)
{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"Coords":[
"31.856128;34.760947",
"31.8166376;34.729755",
"31.857223;34.727432",
"31.843444;34.751793",
"31.831039;34.722577",
"31.831504;34.756643",
"31.817725;34.7223",
"31.815936;34.752588",
"31.819054;34.739162",
"31.824913;34.747459",
";",
"31.813987;34.719103",
"31.833778;34.74009",
"31.815936;34.752589",
"31.819054;34.739163",
"31.824913;34.747458",
],
"ID":"1405796061262"
}
coords线是所有城市的总和。
我需要像这样回应json: (PHP输出需要像:)
ID: 1405796061262.
Areas: area267, area268.
Citys of Area267: city1, city2, ... city13. (echo all cities in the area)
Citys of Area268: city14, city15, city16. (echo all cities in the area)
我无法了解区域和城市(在JSON文件中)。
感谢您的帮助:)
编辑:工作代码
<?php
$json_data = '{
"area 267":[
"city1",
"city2",
"city3",
"city4",
"city5",
"city6",
"city7",
"city8",
"city9",
"city10",
"city11",
"city12",
"city13"
],
"area 268":[
"city14",
"city15",
"city16"
],
"ID":"1405796061262"
}';
$data = json_decode($json_data);
//var_dump($data);
echo 'ID: ';
echo $data->ID;
echo '.<br>';
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'ID') !== 0 && strpos($k, 'Coords') !== 0) {
$areas[] = $k;
}
}
echo implode(', ',$areas).'.<br /><br />';
foreach ($areas as $k => $v) {
echo "Cities of ".$v.': ';
$cities = array();
$cities = null;
foreach ($data->$v as $area) {
$cities[] = $area;
}
echo implode(', ',$cities).'.<br />';
}
?>
答案 0 :(得分:0)
首先你可以使用json_decode
将json输出转换为php对象,然后你可以轻松地循环它并获得确切的字段值。
答案 1 :(得分:0)
可能这样的事情应该有效
$data = json_decode($json_data);
echo 'ID '.$data['ID']."<br />";
echo 'Areas: ';
$areas = array();
foreach ($data as $k => $v) {
if (strpos($k, 'area ') === 0) {
$areas[] = $k;
}
}
echo implode(',',$areas).'.<br /><br />';
foreach ($areas as $area) {
echo "Cities of ".strtoupper($area).':';
$cities = array();
foreach ($data[$area] as $city) {
$cities[] = $city;
}
echo implode(','.$cities).'.<br />';
}