PHP - Parsing JSON file with data in multidimensional object
Discuss coding issues, and scripts related to PHP and MySQL.
-
PloMar
- Posts:48
PHP - Parsing JSON file with data in multidimensional object
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.
Admin
Posts:805
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
Similar Topics
- GET_id not working in UnLink (delete file)
PHP - MySQL
First post
I searching for an hour for a solution; unlink seems not to work with GET id
<?php
$id = (int) $_GET ;
echo $_GET ;
$file = fopen( '.$_GET...
Last post
Here is an answer `o god after 2 hours shame on me for this one`
<?php
$file_pointer = $_GET .'.txt';
if (!unlink($file_pointer)) {
echo (...