我有以下存储在json文件中的JSON数据,这个JSON的架构不同,所以这个问题不重复: -
为什么跟随PHP生成“NULL”? : -
<?php
$url = "file.json";
echo $url . "<br>";
$json_string = file_get_contents($url);
echo $json_string . "<br>";
$json_array = json_decode($json_string, true); // need an associative array
var_dump(json_decode($json_array));
?>
问题:如果“代码”:“XXX”存在,如何在PHP中找到“city”,“state”和“region”的值: -
[
{
"code": "XXX",
"city": "Indore",
"state": "Madhya Pradesh",
"region": "W"
},
{
"code": "XXY",
"city": "Vapi",
"state": "Gujarat",
"region": "W"
},
{
"code": "XXZ",
"city": "Kolkata",
"state": "West Bengal",
"region": "E"
},
{
"code": "XXV",
"city": "Sundar Nagar",
"state": "Himachal Pradesh",
"region": "N"
}
]
答案 0 :(得分:0)
尝试以下代码。首先解码json然后循环它
$json = '[
{
"code": "XXX",
"city": "Indore",
"state": "Madhya Pradesh",
"region": "W"
},
{
"code": "XXY",
"city": "Vapi",
"state": "Gujarat",
"region": "W"
},
{
"code": "XXZ",
"city": "Kolkata",
"state": "West Bengal",
"region": "E"
},
{
"code": "XXV",
"city": "Sundar Nagar",
"state": "Himachal Pradesh",
"region": "N"
}
]';
$arr = json_decode($json,true);
$find_val = "XXX";
$city = $region =$state = "";
foreach ($arr as $key => $value) {
if($value['code'] == $find_val)
{
$city = $value['city'];
$state =$value['state'];
$region = $value['region'];
}
}
echo $city;
echo "<br>";
echo $state;
echo "<br>";
echo $region;