Search code examples
phparraysjsonstdclass

Uncaught Error: Cannot use object of type stdClass as array


Fatal error: Uncaught Error: Cannot use object of type stdClass as array

$code = json_decode($src);
echo $code["items"];

var_dump shows the following (truncated):

object(stdClass)#7 (3) { ... } 

I don't know what stdClass is and how to use it.

Edit:

stdClass is a class which creates an instance of simple object. Properties of classes are to be accessed using ->, not [...] notation.

As per documentation for json_decode, simply setting the second argument to true will result in the result being associative array, which can be in turn accessed like an array.

At the time of posting this question, I didn't try searching on how to decode JSON - as that's pretty simple and I got that working. I was just getting another error (above), and had no luck searching on how to fix that. I believe people have similar problems, as this question is getting some views as well.


Solution

  • Use json_decode($src, true) to get associative array.

    This is preferred way, as currently you get mixed arrays and objects and you may end up in crazy house, trying to work with these :)

    Alternatively use -> operator to get properties of object.

    Currently your item is at:

    $code->items[0]->pagemap->cse_image[0]->src