php - 如何使用动态键循环 PHP 对象

标签 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 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574089/

相关文章:

php - 如何在 MYSQL 中的同一 INSERT QUERY 中的另一列中使用自动递增 Id?

php - 在单个查询 mysql 和 php 中选择多个关联记录

ruby-on-rails - ruby rails : How can I use JSONPath to access (and save to database) nested objects/properties within a JSON array?

c++ - 将 JSON 格式的属性树转换为点分隔字符串的 Boost 库函数?

javascript - 使用 ng-click 链接 angular js 的事件类?

java - 通用方法和 JSON

php - 在 HTTP cURL POST 中发送具有相同名称/键的多个值

php - 切换到HTTPS后无法登录PHPmyAdmin

php - 通过 mysqli 的查询不会更新 Performance_schema

c# - 我应该选择哪种格式来请求 C# 中的 API - JSON 或 XML