Dan B.
Dan B.

Reputation: 93

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.

Upvotes: 1

Views: 21254

Answers (2)

ob-ivan
ob-ivan

Reputation: 833

The json_decode function has a second parameter dedicated to just that: setting it to true will return an associative array where there is an object (in { "curly": "braces" }) in JSON.

To illustrate that:

$a = json_decode('{ "b": 1 }', false);
var_dump($a->b);
// prints: int(1)

$a = json_decode('{ "b": 1 }', true);
var_dump($a['b']);
// prints: int(1)

Note the difference in how values are accessed.

Further reading: http://php.net/json_decode

Upvotes: -1

Rauli Rajande
Rauli Rajande

Reputation: 2020

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

Upvotes: 10

Related Questions