我尝试使用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循环。
我希望你能举个例子。
我不敢相信这么多人在没有正确阅读JSON的情况下就发布了答案。
如果单独迭代$json_a,就得到了一个对象的对象。即使你传入了true作为第二个参数,你也得到了一个二维数组。如果你循环遍历第一个维度你不能像这样回显第二个维度。所以这是错误的:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
为了反映每个人的状态,试试这个:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>