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?
Answer>
15 Answers
Use the second parameter of json_decode
to make it return an array:
$result = json_decode($data, true);
Use the second parameter of json_decode
to make it return an array:
$result = json_decode($data, true);
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);
You must access it using ->
since its an object.
Change your code from:
$result['context'];
To:
$result->context;
The problem I have is trying to use the property in a conditional
if ($result->context = $var)
This causes the property to be set to the var and returns true, no matter.
Have same problem today, solved like this:
If you call json_decode($somestring)
you will get an Object and you need to access like $object->key
, but if u call json_decode($somestring, true)
you will get an dictionary and can access like $array['key']
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.
It's not an array, it's an object of type stdClass.
You can access it like this:
echo $oResult->context;
More info here: What is stdClass in PHP?
To get an array as result from a json string you should set second param as boolean true.
$result = json_decode($json_string, true);
$context = $result['context'];
Otherwise $result will be an std object. but you can access values as object.
$result = json_decode($json_string);
$context = $result->context;
0 comments:
Post a Comment
Thanks