dongqijuan3786 2014-12-22 06:23
浏览 60
已采纳

使用PHP循环访问JSON数组

My Code:

$json2 = json_decode($content, true);
$thing = $json2{"reply1"}->{"tokens"};
foreach ($thing as $laa) {
  echo $laa->token;
}

Whenever I run this code against my JSON it returns:

PHP Notice:  Trying to get property of non-object in /root/backup.php on line 33
PHP Warning:  Invalid argument supplied for foreach() in /root/backup.php

All I want to do is loop through the JSON and get one part which is the token for each [token]. (Starting part of JSON)

JSON:

Array
(
    [errors] => Array
        (
        )

    [reply] => success
    [item] => Array
        (
            [status] => CURRENT
            [messageURI] => 
        )

    [reply1] => Array
        (
            [tokens] => Array
                (
                    [0] => Array
                        (
                            [token] => 123456

                        )

                    [1] => Array
                        (
                            [token] => 123456

                                )

Any help is appreciated. Thanks.

  • 写回答

1条回答 默认 最新

  • dongxiao1591 2014-12-22 06:27
    关注

    You're accessing an array. You do this with [], not with {}.

    To get at the tokens array, you need $json2['reply1']['tokens'].

    Again, you access individual items in this array with [], not ->. Using $laa->token; is going to fail again.

    Try the following

    $tokens = $json2['reply1']['tokens'];
    
    foreach ($tokens as $token) {
      echo $token['token']
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测