1

I have Following Value :-

What i want :- I want to fetch City name from City code ?

For example :- if input is "BA", i want to display "Bagmati", if input is "DH", i want to display "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"}
}';

What i tried in PHP :-

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

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

But I am not sure, how can i get this. any help will be appreciated.

Just for note, i took these value from javascript file :- state.js file

"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"}
},

Thank you!

2 Answers 2

3

This will decode your json to native php arrays instead of combination of arrays and objects, and you have only to iterate $value["NP"] array,

$value = json_decode($json,1);

foreach ($value["NP"] as $el) {
    echo $el["name"];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Where does this answer test whether the code matches the input?
0

Use the $assoc argument to json_decode() to get an associative array instead of objects:

$value = json_decode($json, true);

Then you can iterate through it:

foreach ($value['NP'] as $subarray) {
    if ($subarray['code'] == $input) {
        echo $subarray['name'];
        break;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.