我尝试使用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循环。
对于这一点,我希望有一个例子。
发布于 2015-02-21 20:52:39
没有人指出你开始的“标签”是错误的,这完全超出了我的理解。您使用{}创建一个对象,而您可以使用[]创建一个数组。
[ // <-- 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将被解析为数组而不是对象。有了这个数组,你可以做任何你想做的事情,比如循环等等。
https://stackoverflow.com/questions/4343596
复制相似问题