正在分析JSON提要



我在URL中有一个json提要,其中包含以下数据。

<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;
}   

尝试作为

$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'];
}

这很有效。

由于您的JSON已经成为一个关联数组,因此您必须制作2个foreach。

  • Top foreach解析'[object1,object2,object3]'中的3个"对象">
  • 底部foreach解析每个"对象"内容

    $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"json"不是一个JS对象,它是一个关联数组的数组。

如果json_decode的第二个参数设置为true,则json将在关联数组中而不是对象中进行转换。试试这个:

$obj = json_decode($json, false);
foreach($obj as $ob) {
    echo $ob->ID;
}   
$my_array_for_parsing = json_decode(/** put the json here */);

这为您提供了作为php关联数组的JSon。


$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
}

相关内容

  • 没有找到相关文章

最新更新