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?
The PHP engine throws the “cannot use object of type stdClass as array” error message due to your code trying to access a variable that is an object type as an array . It is most likely that you've tried to access the data with the generic bracket array accessor and not an object operator.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
Use the second parameter of json_decode
to make it return an array:
$result = json_decode($data, true);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With