Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use object of type stdClass as array?

Tags:

json

php

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?

like image 212
Dail Avatar asked Jul 25 '11 11:07

Dail


People also ask

Can not use object of type as array PHP?

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.

What is stdClass object in PHP?

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.


2 Answers

Use the second parameter of json_decode to make it return an array:

$result = json_decode($data, true); 
like image 141
Jon Avatar answered Sep 19 '22 09:09

Jon


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); 
like image 43
svens Avatar answered Sep 19 '22 09:09

svens