Looping PHP objects using dynamic keys: a step-by-step guide
P粉312195700
P粉312195700 2023-10-10 08:50:47
0
2
672

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.

P粉312195700
P粉312195700

reply all(2)
P粉920199761

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 in true 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:

foreach ($json_a as $k => $v) {
   echo $k, ' : ', $v;
}

To echo everyone's status, try the following:

 $person_a) {
    echo $person_a['status'];
}

?>
P粉668019339

To iterate over a multi-dimensional 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 keyboard

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template