Cannot use object of type stdClass as array?
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?
Solution 1:
Use the second parameter of json_decode
to make it return an array:
$result = json_decode($data, true);
Solution 2:
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);
Solution 3:
You must access it using ->
since its an object.
Change your code from:
$result['context'];
To:
$result->context;
Solution 4:
Use true
as the second parameter to json_decode
. This will decode the json into an associative array instead of stdObject
instances:
$my_array = json_decode($my_json, true);
See the documentation for more details.