Reputation: 740
I need to loop trough a nested JSON array in PHP. The JSON keys are not always the same, see example below:
[
{
"id": 1,
"more": {
"city": "New York",
"street": "W 58th St"
},
"group": 4,
"name": "Ellie",
"status": "offline",
"phone": "1234567890",
"disabled": false
},
{
"id": 2,
"more": {
"city": "New York",
"street": "W 101st St",
"postal code": "12345"
},
"group": 7,
"name": "Diane",
"age": "25",
"phone": "",
"contact": "2",
}
]
My code so far is this:
$user_details = json_decode($json, true);
foreach ($user_details as $details) {
foreach ($details as $key => $value) {
echo $key .': '. $value, PHP_EOL;
}
}
The problem is, I get an error for the more
array when I try to run the code above:
id: 1
<b>Warning</b>: Array to string conversion in <b>[...][...]</b> on line <b>15</b><br />
more: Array
group: 4
name: Ellie
status: offline
...
Ideally, the output should be like so:
id: 1
city: New York
street: "W 58th St
group: 4
name: Ellie
status: offline
...
Any suggestion on how to improve my code to output the correct data?
Upvotes: 0
Views: 45
Reputation: 179
You have 3 arrays. For example, look at your first item, where id = 1. For 'more', you have:
$user_details[0]['more']['city'] = 'New York';
Your outer loop grabs elements 0 thru 1. The inner loop has keys = 'id', 'more', 'group', 'name', etc. When you try to execute echo the 2nd time, your variables are:
$key = 'more';
$value = [ 'city' => 'New York', 'street' => 'W 58th St' ];
Your echo statement tries to treat $value as a string, but it's an array.
Wrap your echo statement in an if () statement, such that:
if ( is_array( $value ) ) {
// For an array, do something different
foreach ( $value as $key1 => $value1 ) {
echo $key1 . ': ' . $value1, PHP_EOL
}
} else {
// Do your echo here.
echo $key .': '. $value, PHP_EOL;
}
Upvotes: 1
Reputation: 697
This line echo $key .': '. $value, PHP_EOL;
is treating a value of type array as a string as it is concatenating the value to a string.
Instead, you could do something like this to check if the value is itself an array, and then print each member of it if so.
if ( is_array($value) ) {
// One more nested loop to print the keys and values
}
Of course, if there are any other nested objects or arrays, you will run into the same problem. So better to implement some type of logic to handle nested objects or arrays in general.
Upvotes: 1