How to loop through PHP object with dynamic keys
json, php
Solution
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$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
Problem
I tried to parse a JSON file using PHP. But I am stuck now. 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 } } ``` And this is what I have tried so far: ``` <?php $string = file_get_contents("/home/michael/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'`, `'Jennifer'`) and all available keys and values (like `'age'`, `'count'`) beforehand, I think I need to create some foreach loop. I would appreciate an example for this.
Related problems
- Detect bad json data in PHP json_decode()?
- How to remove multiple UTF-8 BOM sequences
- How to cast variable to array
- Fastest way to check if a string is JSON in PHP?
- How to extract and access data from JSON with PHP?
- Encoding troubles - one format to another
- How to extract and access data from JSON with PHP?