我在包含以下数据的网址中有一个json Feed。
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"ID":1123,"OrderNumber":"1394","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"someone.biz/Home/ShowTemplate/283","ShipDate":"2/28/2015","InHomeDate":"3/2/2015","Quantity":"10,000","Price":"$3,000","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"3/30/2015","InHomeDate":"3/31/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"4/13/2015","InHomeDate":"4/14/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"}]
</string>
我需要得到它并通过php解析它。但它使用以下代码给出了无效的foreach错误。任何人都可以帮我解决如何正确显示。
$json = file_get_contents('http://someurl.biz/api/api/1123');
$obj = json_decode($json, true);
foreach($obj as $ob) {
echo $ob->ID;
}
答案 0 :(得分:4)
尝试
$json = file_get_contents('http://superiorpostcards.biz/api/api/1123');
$obj = json_decode($json, true);
$array = json_decode($obj, true);
foreach($array as $value){
echo $value['ID'];
}
答案 1 :(得分:1)
这很有效。
当你的JSON成为一个关联数组时,你必须做出2个foreach。
底部的foreach解析每个&#34;对象&#34;含量
$data = json_decode('[{"ID":1123,"OrderNumber":"1394","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"someone.biz/Home/ShowTemplate/283","ShipDate":"2/28/2015","InHomeDate":"3/2/2015","Quantity":"10,000","Price":"$3,000","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"3/30/2015","InHomeDate":"3/31/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"},{"ID":1123,"OrderNumber":"1413","ProjectType":"Postcard","Template":"WtlossStudy solo","TemplateURL":"","ShipDate":"4/13/2015","InHomeDate":"4/14/2015","Quantity":"5,000","Price":"$1,500","CallTracking":"0"}]');
foreach($data as $obj) {
foreach($obj as $key=>$val) {
echo $key."->".$val." | ";
}
}
是的,JS更简单。但是php&#34; json&#34;不是JS对象,它是一个关联数组的数组。
答案 2 :(得分:0)
$my_array_for_parsing = json_decode(/** put the json here */);
这使得JSon成为php associative 数组。
$my_array_for_parsing = json_decode($json);
foreach ($my_array_for_parsing as $name => $value) {
// This will loop three times:
// $name = a
// $name = b
// $name = c
// ...with $value as the value of that property
}
答案 3 :(得分:0)
如果json_decode的第二个参数设置为true
,则json
将在关联数组中而不是对象中进行转换。试试这个:
$obj = json_decode($json, false);
foreach($obj as $ob) {
echo $ob->ID;
}