“Fatal error: Uncaught Error: Cannot use object of type stdClass as array in” is an error that occurs in PHP when working with a JSON object.
PHP version 5.2.0 and greater features a function, json_decode
, that decodes a JSON string into a PHP variable.
json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed
By default, it returns an object. The second parameter accepts a boolean that when set as true, tells it to return the objects as associative arrays, but when omitted, you get this error “ Fatal error: Uncaught Error: Cannot use object of type stdClass as array in …………….”.
Example
Let’s assume we have a JSON string or object.
$json = {“name”:”Aluya Matthew”,”age”:”24”,”department”:”Engineering”,”salary”:”$7500”}
to decode the above JSON, we use the json_decode() function.
$data = json_decode($json)The above code will output “ Fatal error: Uncaught Error: Cannot use object of type stdClass as array in …………….”.
The above error is triggered because the second parameter for json_decode() was omitted. To fix the error, pass true as the second parameter to json_decode. That will ensure that the JSON string is converted to an associative array.
Method 1.
Pass ‘true’ as parameter to the json_decode() function.
<?php $data = json_decode($json, true); ?>
Method2.
Convert(cast) stdClass object to array
<?php $result = (array) json_decode($json); ?>
Happy coding!!!