我试图使用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循环。
发布于 2018-08-13 12:27:12
如果$json_a
单独使用迭代,则会有一个对象的对象。即使true
作为第二个参数传入,也有一个二维数组。如果你在第一个维度上循环,你就不能像这样回应第二个维度。所以这是错的:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
若要回显每个人的状态,请尝试如下:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
发布于 2018-08-13 12:41:22
试一试
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a=json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
https://stackoverflow.com/questions/-100002093
复制相似问题