When working with JSON and PHP, things can get a bit tricky. One such situation might be decoding JSON data, which probably occurs more often than not in a web application.
I came across this fatal php error:
Fatal error: Cannot use object of type stdClass as array…
The cause was a json_decode
call that I thought was entirely innocent.
Apparently, some genious thought it was a great idea to make the return value of the json_decode
function be an object. It turns out that you have to explicitly state that you want an array.
$raw = json_decode($json); // bad way
echo( $raw["somekey"] ); // fatal error ...
$better = json_decode($json, true);
echo( $raw["somekey"] ); // no error!
According to the PHP.net documentation on json_decode, you need to set the second assoc argument to true so that PHP will return arrays.
That’s all there is to this silly error.
That did the trick, Thanks! Ugh.. does this mean I am going to have to start learning OOP? I guess it is about time.
This was very helpful. Thanks for posting!
thnks, this was very helpfulll
thanks, very helpful
Thanks for that one, that’s a really dumb error on my part. I guess people are slowly going OOP crazy.