2

我在包含以下数据的 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;
}   
4

4 回答 4

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'];
}
于 2015-07-31T13:24:09.433 回答
1

这行得通。

由于您的 JSON 已成为关联数组,因此您必须创建 2 个 foreach。

  • 顶部 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 对象,它是一个关联数组的数组。

于 2015-07-31T13:25:21.767 回答
0
$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
}
于 2015-07-31T13:08:40.917 回答
0

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

$obj = json_decode($json, false);

foreach($obj as $ob) {
    echo $ob->ID;
}   
于 2015-07-31T13:08:48.187 回答