【问题标题】:PHP Loop stdClass Object [duplicate]PHP循环stdClass对象[重复]
【发布时间】:2016-03-14 12:13:11
【问题描述】:

我调用了一个返回 json 数据的 web 服务。我用:

$response_json = json_decode ( $response );

如果我 print_r($response) 我得到这个:

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 类的对象无法转换为字符串。我也尝试了许多其他方法,但我似乎无法循环访问数据。提前致谢。

【问题讨论】:

    标签: php arrays json object


    【解决方案1】:

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

    $response = json_decode ($response, true);
    
    foreach($response as $orders) {
        echo $orders[0]['orderid'];
    }
    

    【讨论】:

    • 好吧,如果我这样做: $response_json = json_decode ( $response , true); foreach($response_json as $orders) { echo $orders.['data'].[0].['orderid'];
    • echo $orders['data'][0]['orderid'];我没有输出??
    • 对不起,我更正了我的答案。它没有 ['data'] 因为你已经循环遍历数组。确保执行“print_r($orders);”
    • 抱歉不知道我在这里做错了什么... foreach($response_json as $orders) { foreach($orders as $order) { echo $order['orderid']; }} 仅输出 2 个带有警告的订单:为 foreach() 提供的参数无效
    • 循环遍历 $response_json['data']
    【解决方案2】:
    1. 不要在括号之间使用点。
    2. 跳过数组中的“数据”。

    例子:

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

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 2014-06-18
      • 1970-01-01
      • 2015-10-24
      • 2010-10-31
      • 2017-05-01
      • 2014-01-31
      • 1970-01-01
      • 2015-05-16
      相关资源
      最近更新 更多