1

我有以下价值:-

我想要什么:-我想从城市代码中获取城市名称?

例如:- 如果输入是“BA”,我想显示“Bagmati”,如果输入是“DH”,我想显示“Dhawlagiri”

$value = '{"NP":{
"1" : {"code":"BA","name":"Bagmati"},
"2" : {"code":"BH","name":"Bheri"},
"3" : {"code":"DH","name":"Dhawalagiri"},
"4" : {"code":"GA","name":"Gandaki"},
"5" : {"code":"JA","name":"Janakpur"},
"6" : {"code":"KA","name":"Karnali"},
"7" : {"code":"KO","name":"Kosi"},
"8" : {"code":"LU","name":"Lumbini"},
"9" : {"code":"MA","name":"Mahakali"},
"10" : {"code":"ME","name":"Mechi"},
"11" : {"code":"NA","name":"Narayani"},
"12" : {"code":"RA","name":"Rapti"},
"13" : {"code":"SA","name":"Sagarmatha"},
"14" : {"code":"SE","name":"Seti"}
}';

我尝试过的PHP:-

$value = json_decode($json);
//print_r($value);

foreach ($value->IN->code as $city) {
    echo $city->name;
}

但我不确定,我怎么能得到这个。任何帮助将不胜感激。

请注意,我从javascript文件中获取了这些值:- state.js 文件

"NP":{
"1" : {"code":"BA","name":"Bagmati"},
"2" : {"code":"BH","name":"Bheri"},
"3" : {"code":"DH","name":"Dhawalagiri"},
"4" : {"code":"GA","name":"Gandaki"},
"5" : {"code":"JA","name":"Janakpur"},
"6" : {"code":"KA","name":"Karnali"},
"7" : {"code":"KO","name":"Kosi"},
"8" : {"code":"LU","name":"Lumbini"},
"9" : {"code":"MA","name":"Mahakali"},
"10" : {"code":"ME","name":"Mechi"},
"11" : {"code":"NA","name":"Narayani"},
"12" : {"code":"RA","name":"Rapti"},
"13" : {"code":"SA","name":"Sagarmatha"},
"14" : {"code":"SE","name":"Seti"}
},

谢谢!

4

2 回答 2

3

这会将您的 json 解码为本机 php 数组,而不是数组和对象的组合,并且您只需迭代$value["NP"]数组,

$value = json_decode($json,1);

foreach ($value["NP"] as $el) {
    echo $el["name"];
}
于 2013-06-25T19:09:40.290 回答
0

使用$assoc参数来json_decode()获取关联数组而不是对象:

$value = json_decode($json, true);

然后你可以遍历它:

foreach ($value['NP'] as $subarray) {
    if ($subarray['code'] == $input) {
        echo $subarray['name'];
        break;
    }
}
于 2013-06-25T19:15:37.783 回答