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?