php - 如何使用 PHP 解析 JSON 文件?

标签 php json

我尝试使用 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 循环。

我会很感激这个例子。

最佳答案

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

输出:

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

run on codepad

关于php - 如何使用 PHP 解析 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4343596/

相关文章:

php - 我的代码中的 MYSQL 错误

javascript - 如何在没有给定模式的情况下将字符串拆分为相同的部分?

sql-server - SQL Server JSON_Modify,如何更新全部?

javascript - 为什么我的带有 JSONP 脚本的 PHP/AJAX 返回 HTML、JSON 和无效的 JSON?

javascript - 如何从innerHTML对象获取值?

php - 从 span 字段提交一个值

php - 如何在 PHP 中显示之前简化 MySQL 错误?

php - 无法运行 OpenTok 的 WebRTC 演示

javascript - 如何创建和克隆 JSON 对象?

javascript - $.getJSON 函数与 json 对象