How can I parse a JSON file with PHP?
To iterate over a multidimensional array, you can use RecursiveArrayIterator
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>