I'm trying to parse a JSON file using PHP. But now I'm stuck.
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 } }
Here's what I've 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 since I don't know the names (e.g. 'John'
, 'Jennifer'
) and all available keys and values (e.g. 'age'
, 'count'
) Beforehand, I think I need to create some foreach loops.
I wish there was an example.
I can't believe so many people are posting answers without reading the JSON properly.
If you iterate over
$json_a
alone, you'll get an object of objects. Even if you pass intrue
as the second parameter, you have a 2D array. If you loop over the first dimension, you can't echo the second dimension like this. So this is wrong:To echo everyone's status, try the following:
To iterate over a multi-dimensional array, you can use RecursiveArrayIterator
Output:
Run on keyboard