2015-12-09 130 views
0

我有一个正在返回json数据的web服务调用。我使用:PHP循环stdClass对象

$response_json = json_decode ($response); 

如果我的print_r($响应)我得到这样的:

stdClass Object 
(
    [meta] => stdClass Object 
    (
     [no_of_pages] => 3 
     [current_page] => 1 
     [max_items_per_page] => 250 
     [no_of_items] => 740 
    ) 

[data] => Array 
    (
     [0] => stdClass Object 
      (
       [orderid] => 322191645 
       [customer] => stdClass Object 
        (
         [city] => FELIXSTOWE 

我通过命令试图循环:

foreach($response_json as $orders) { 
    echo $orders.['data'].[0].['orderid']; 
    } 

,但我不断收到:

可捕获的致命错误:类stdClass的对象无法转换为字符串。我也尝试了很多其他方式,但我似乎无法在循环中访问数据。提前致谢。

回答

3

你可以将json_decode作为关联数组。

$response = json_decode ($response, true); 

foreach($response as $orders) { 
    echo $orders[0]['orderid']; 
} 
+0

行,如果我做:$ response_json = json_decode($响应,TRUE); \t \t \t 的foreach \t($ response_json为$订单){ \t \t回声$订单[ '数据'] [0] [ '订单ID']。。。; – Paul

+0

删除点。 – KiwiJuicer

+0

echo $ orders ['data'] [0] ['orderid'];我没有得到这个输出? – Paul

1
  1. 不要括号之间使用圆点。
  2. 跳过阵列中的“数据”。

实施例:

foreach($response_json as $orders) { 
    echo $orders[0]['orderid']; 
}