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)
My Answer:
{
"data": {
"123": {
"name": "John",
"age": 30
},
"456": {
"name": "Jane",
"age": 25
}
}
}
To get the value of an unknown array key in PHP, you can use the following code:
php
$json = '{
"data": {
"123": {
"name": "John",
"age": 30
},
"456": {
"name": "Jane",
"age": 25
}
}
}';
$array = json_decode($json, true);
foreach ($array['data'] as $key => $value) {
echo "Key: " . $key . "\n";
echo "Name: " . $value['name'] . "\n";
echo "Age: " . $value['age'] . "\n";
}
This code will loop through the data array and output the key, name, and age for each element.
Rate this post
5 of 5 based on 2903 votesComments