如何使用 PHP 解析 JSON 文件?

2022-08-30 05:51:16

我试图使用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];

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

我希望能有这样一个例子。


答案 1

若要迭代多维数组,可以使用递归数组

$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

在代码键盘上运行


答案 2

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

如果单独进行迭代,则有对象的对象。即使作为第二个参数传入,您也有一个二维数组。如果你正在循环通过第一个维度,你不能像那样回显第二个维度。所以这是错误的:$json_atrue

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

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

<?php

$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

?>

推荐