我尝试使用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循环。
对于这一点,我希望有一个例子。
发布于 2010-12-03 16:27:15
要迭代多维数组,可以使用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 => 0run on codepad
发布于 2010-12-03 16:22:43
我不敢相信有这么多人在没有正确阅读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'];
}
?>发布于 2014-12-17 21:30:03
最优雅的解决方案:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);请记住,json-file必须在没有BOM的情况下以UTF-8编码。如果文件有物料清单,则json_decode将返回NULL。
或者:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;https://stackoverflow.com/questions/4343596
复制相似问题