首页  >  问答  >  正文

使用动态键循环 PHP 对象:分步指南

我尝试使用 PHP 解析 JSON 文件。但我现在陷入困境了。

这是我的 JSON 文件的内容:

{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

这是我迄今为止尝试过的:

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

但是因为我不知道名称(例如 'John''Jennifer')以及所有可用的键和值(例如 'age''count')事先,我想我需要创建一些 foreach 循环。

我希望有一个例子。

P粉312195700P粉312195700348 天前546

全部回复(2)我来回复

  • P粉920199761

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

    我不敢相信这么多人在没有正确阅读 JSON 的情况下就发布答案。

    如果你单独迭代$json_a,你就会得到一个对象的对象。即使您传入 true 作为第二个参数,您也有一个二维数组。如果你循环遍历第一个维度,你就不能像这样回显第二个维度。所以这是错误的:

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

    要回显每个人的状态,请尝试以下操作:

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

    回复
    0
  • P粉668019339

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

    要迭代多维数组,可以使用 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";
        }
    }

    输出:

    John:
    status => Wait
    Jennifer:
    status => Active
    James:
    status => Active
    age => 56
    count => 10
    progress => 0.0029857
    bad => 0

    在键盘上运行

    回复
    0
  • 取消回复