我尝试使用 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
关于php - 如何使用动态键循环 PHP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47502909/