gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:29:32 24 4
gpt4 key购买 nike

我尝试使用 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/44735050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com