Page 1 of 1

PHP - Parsing JSON file with data in multidimensional object

Posted: 12 Jan 2015, 07:26
by PloMar
I try to parse a JSON file using PHP. The data in this JSON is in a two-dimensional object, like this:

Code: Select all

{
  "John": {
    "status":"Wait"
  },
  "Jennifer": {
    "status":"Active"
  },
  "Klaus": {
    "status":"Active",
    "age":48,
    "count":12,
    "progress":0.002989
  }
}
And this is my PHP code:

Code: Select all

<?php
$string = file_get_contents("/dir/test.json");
$json_a = json_decode($string, true);
echo  $json_a['John'][status];
echo  $json_a['Jennifer'][status]; 
But because i don't know the names (like John, Klaus) and all available keys and values (like age, count) on beforehand, i think i need to create some foreach loop.
So i appreciate an example for this.
- Thanks in advance.

PHP - Parsing JSON file with data in multidimensional object

Posted: 12 Jan 2015, 07:39
by Admin
To iterate over a multidimensional array, you can use RecursiveArrayIterator.

Code: Select all

$string = file_get_contents('/dir/test.json');
$json_iterator = new RecursiveIteratorIterator(
  new RecursiveArrayIterator(json_decode($string, TRUE)),
  RecursiveIteratorIterator::SELF_FIRST);

foreach($json_iterator as $key => $val) {
  if(is_array($val)) echo "$key:\n";
  else echo "$key => $val\n";
} 
Output:

Code: Select all

John: 
status => Wait
Jennifer: 
status => Active
Klaus: 
status => Active
age => 48
count => 12
progress => 0.002989