json - PHP - Get the value of an unknown array key
Based on this result from an API
"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
},
Let's suppose i always want the "common" name but, depending on the country the "key" will vary (now it's "ita" but it could be anything)
What is the cleanest way to always get the "common" value independently of the key name above? (so a dynamic function that always get the common value)
Answer
Solution:
With fixed structures you can do that:
$arr = json_decode('{"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
}}',true);
$country = key($arr['name']['nativeName']); //ita
$common = $arr['name']['nativeName'][$country]['common']; //Italia
echo '$country = '.$country.', $common = '.$common;
Demo: https://3v4l.org/W4sqI
Answer
Solution:
You could iterate over that part of the data structure like this to get both the key and the value of common
$json = '{
"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
}
}';
foreach (json_decode($json)->name->nativeName as $key => $native){
echo "Key = $key, common = {$native->common}";
}
RESULT
Key = ita, common = Italia
Answer
Solution:
You can use get_mangled_object_vars()
with key()
if you have just one nativeName
like:
$a = json_decode('{"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
}}');
print_r(key(get_mangled_object_vars($a->name->nativeName))); // ita
Reference:
Or you can use ArrayObject
combine with getIterator()
and key()
like:
$a = json_decode('{"name": {
"common": "Italy",
"official": "Italian Republic",
"nativeName": {
"ita": {
"official": "Repubblica italiana",
"common": "Italia"
}
}
}}');
$arrayobject = new ArrayObject($a->name->nativeName);
$iterator = $arrayobject->getIterator();
echo $iterator->key(); //ita
Reference:
Source