search

Home  >  Q&A  >  body text

Looping PHP objects using dynamic keys: a step-by-step guide

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粉312195700P粉312195700431 days ago642

reply all(2)I'll reply

  • P粉920199761

    P粉9201997612023-10-11 07:17:05

    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'];
    }
    
    ?>

    reply
    0
  • P粉668019339

    P粉6680193392023-10-11 07:17:05

    To iterate over a multi-dimensional array, you can use RecursiveArrayIterator< /p>

    $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

    reply
    0
  • Cancelreply