猿问

如何用PHP解析JSON文件?

如何用PHP解析JSON文件?

我试图使用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循环。


我会很感激这个例子。


呼唤远方
浏览 2012回答 5
5回答

湖上湖

要迭代多维数组,可以使用RecursiveArrayIterator$jsonIterator&nbsp;=&nbsp;new&nbsp;RecursiveIteratorIterator( &nbsp;&nbsp;&nbsp;&nbsp;new&nbsp;RecursiveArrayIterator(json_decode($json,&nbsp;TRUE)), &nbsp;&nbsp;&nbsp;&nbsp;RecursiveIteratorIterator::SELF_FIRST);foreach&nbsp;($jsonIterator&nbsp;as&nbsp;$key&nbsp;=>&nbsp;$val)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if(is_array($val))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"$key:\n"; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"$key&nbsp;=>&nbsp;$val\n"; &nbsp;&nbsp;&nbsp;&nbsp;}}输出:John:status&nbsp;=>&nbsp;WaitJennifer:status&nbsp;=>&nbsp;ActiveJames:status&nbsp;=>&nbsp;Activeage&nbsp;=>&nbsp;56count&nbsp;=>&nbsp;10progress&nbsp;=>&nbsp;0.0029857bad&nbsp;=>&nbsp;0在键盘上运行

繁星coding

最优雅的解决方案:$shipments = json_decode(file_get_contents("shipments.js"), true);print_r($shipments);请记住,json文件必须以UTF-8编码而不使用BOM。如果文件有BOM,则json_decode将返回NULL。或者:$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));echo $shipments;

潇湘沐

没有人指出你开始的“标签”是错误的,完全超出我的范围。您正在使用{}创建对象,而可以使用[]创建数组。[ // <-- Note that I changed this&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name" : "john", // And moved the name here.&nbsp; &nbsp; &nbsp; &nbsp; "status":"Wait"&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name" : "Jennifer",&nbsp; &nbsp; &nbsp; &nbsp; "status":"Active"&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name" : "James",&nbsp; &nbsp; &nbsp; &nbsp; "status":"Active",&nbsp; &nbsp; &nbsp; &nbsp; "age":56,&nbsp; &nbsp; &nbsp; &nbsp; "count":10,&nbsp; &nbsp; &nbsp; &nbsp; "progress":0.0029857,&nbsp; &nbsp; &nbsp; &nbsp; "bad":0&nbsp; &nbsp; }] // <-- And this.通过此更改,json将被解析为数组而不是对象。使用该数组,您可以执行任何操作,例如循环等。
随时随地看视频慕课网APP
我要回答