我尝试使用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
在代码板上运行
我完全无法理解,居然没有人指出你开头的“标签”是错的。你可以用{}创建一个对象,而你可以用[]创建一个数组。
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
有了这个更改,json将被解析为数组而不是对象。有了这个数组,你可以做任何你想做的事情,比如循环等等。