简体   繁体   中英

Php and JSON : object(stdClass)

I have decoded a JSON file into a variable ( $tmp ). var_dump($tmp) gives:

object(stdClass)#31 (3) {
    ["c"]=> int(2)
    ["r"]=> int(2)
    ["d"]=> object(stdClass)#32 (4) {
                ["1"]=> string(2) "un"
                ["2"]=> string(4) "deux"
                ["3"]=> string(5) "trois"
                ["4"]=> string(6) "quatre"
            }
}

I want to retrieve for example "un" so I do $tmp->d["1"] but it doesn't work. I've got the following error:

Fatal error: Cannot use object of type stdClass as array in File.php on line 17

json_decode takes an additional paramater that will turn your json string into an array instead of an object

json_decode($json_str, true)

As comment noted, your d property of your json object is an object not an array, so you can't access it with array notation (as you see there is an error)

I believe

$tmp->d->{'1'}
// "un"

should work in accessing it

php has a default function json_encode and json_decode

$arrayOfValues = array();
$jsonString = json_encode($arrayOfValues);

and

$arrayOfValues = json_decode($jsonString);

with this function you can use variabled with json.

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