本文翻译自:How can I parse a JSON file with PHP? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- How do I extract data from JSON with PHP? 如何使用PHP从JSON提取数据? 6 answers 6个答案
I tried to parse a JSON file using PHP. 我试图使用PHP解析JSON文件。 But I am stuck now. 但是我现在被困住了。
This is the content of my JSON file: 这是我的JSON文件的内容:
{
"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];
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. 但是由于我事先不知道名称(例如'John'
, 'Jennifer'
)和所有可用的键和值(例如'age'
, 'count'
),所以我认为我需要创建一些foreach循环。
I would appreciate an example for this. 我希望为此举一个例子。
#1楼
参考:https://stackoom.com/question/IDy0/如何使用PHP解析JSON文件-重复
#2楼
Try it: 试试吧:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
#3楼
Try: 尝试:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
#4楼
When you decode a json string, you will get an object. 解码json字符串时,将获得一个对象。 not an array. 不是数组。 So the best way to see the structure you are getting, is to make a var_dump of the decode. 因此,查看要获取的结构的最佳方法是对解码进行var_dump。 (this var_dump can help you understand the structure, mainly in complex cases). (此var_dump主要在复杂情况下可以帮助您了解结构)。
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
#5楼
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
#6楼
The most elegant solution: 最优雅的解决方案:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. 请记住,必须在没有BOM的情况下将json文件编码为UTF-8。 If the file has BOM, then json_decode will return NULL. 如果文件具有BOM,则json_decode将返回NULL。
Alternatively: 或者:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;