正在解析 JSON 个供稿

Parsing JSON Feed

我在 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":",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":",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":",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;
}   
$my_array_for_parsing = json_decode(/** put the json here */);

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


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

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

$obj = json_decode($json, false);

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个"objects"
  • 底层foreach解析每个"object"内容

    $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":",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":",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":",500","CallTracking":"0"}]');
    
     foreach($data as $obj) {
         foreach($obj as $key=>$val) {
            echo $key."->".$val." | ";
         }
     }   
    

是的,使用 JS 更简单。但是php"json"不是JS对象,是关联数组的数组