简体   繁体   中英

Loop through JSON array using PHP

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.

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']
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM