With Php on a JSON array, how do I get the value of an element according to another related value?
I am using json_decode
Php function to get array of JSON data from countries.
{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
},
If I want to get the code of the 1st item, I can do:
$result = json_decode($sXML);
$final = $result->Countries[0]->Name;
And $final
"Andorre" will matter. But what if I want to get the same Andorre value using its match code?
Can this be done? I know there is a possibility to json_function()
get an associative array instead of a JSON array, but how do you use it to get the Andorre value using its code?
thank
source to share
Here we use two functions to achieve these array_column
and array_combine
to get the expected result.
<?php
ini_set('display_errors', 1);
$string='{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$array=json_decode($string,true);
$codes= array_column($array["Countries"], "Code");//Retrieving column code
$names= array_column($array["Countries"], "Name");//Retrieving column name
$data= array_combine($codes, $names); //combining array with code as keys and names as values.
print_r($data);`
Output:
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
source to share
<?php
$s = '{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$arr = json_decode($s, true);
print_r(array_column($arr['Countries'], "Name", "Code"));
?>
gives
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
source to share
I think you can use something like:
function search_json($obj, $field, $value) {
foreach($obj as $item) {
foreach($item as $child) {
if(isset($child->$field) && $child->$field == $value) {
return $child->Name;
}
}
}
return null;
}
print_r(search_json($result, "Code", "AD"));
# Andorre
source to share