Cannot use object of type stdClass as array?

03/21/2020 14:30:02

I get a strange error using json_decode(). It decode correctly the data (I saw it using print_r), but when I try to access to info inside the array I get:

Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108

I only tried to do: $result['context'] where $result has the data returned by json_decode()

How can I read values inside this array?

Answer #1 (759 Votes)

07/25/2011 16:43:42

Use the second parameter of json_decode to make it return an array:

$result = json_decode($data, true);
759

Answer #2 (204 Votes)

07/25/2011 16:44:29

The function json_decode() returns an object by default.

You can access the data like this:

var_dump($result->context);

If you have identifiers like from-date (the hyphen would cause a PHP error when using the above method) you have to write:

var_dump($result->{'from-date'});

If you want an array you can do something like this:

$result = json_decode($json, true);

Or cast the object to an array:

$result = (array) json_decode($json);
204
2
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.