如何使用 PHP 解析 JSON 文件? [英] How can I parse a JSON file with PHP?
本文介绍了如何使用 PHP 解析 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 PHP 解析 JSON 文件.但我现在卡住了.
I tried to parse a JSON file using PHP. But I am stuck now.
这是我的 JSON 文件的内容:
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
这是我迄今为止尝试过的:
And this is what I have tried so far:
<?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 循环.
But because I don't know the names (like 'John'
, 'Jennifer'
) and all available keys and values (like 'age'
, 'count'
) beforehand, I think I need to create some foreach loop.
我会很感激这个例子.
推荐答案
要迭代多维数组,可以使用 递归数组迭代器
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:
";
} else {
echo "$key => $val
";
}
}
输出:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
这篇关于如何使用 PHP 解析 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文