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)
3
Answers
You could iterate over that part of the data structure like this to get both the key and the value of
common
RESULT
You can use
get_mangled_object_vars()
withkey()
if you have just onenativeName
like:Reference:
Or you can use
ArrayObject
combine withgetIterator()
andkey()
like:Reference:
With fixed structures you can do that:
Demo: https://3v4l.org/W4sqI