Loop trough a nested json array in PHP

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Loop trough a nested json array in PHP on this date .

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?

Answer

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;
}