$data = '{"name":"CocaCola","price":1,"sync":0,"id":10792}';
$data = json_decode($data);
print_r((array)$data);
//Array ( [name] => CocaCola [price] => 1 [sync] => 0 [id] => 10792 )
print_r((array)$data["id"]);
//nothing?
This piece of code is not logic for me. Can I get any explanation of this behaviour and how to fix it?
(array)$data["id"]
This is executed as
(array)($data["id"])
I.e. the result of $data['id']
is cast to an array; not $data
cast to an array and then its id
index accessed.
If you want an array, use json_decode(..., true)
. Otherwise work with objects as objects instead of casting them to arrays all the time over and over.
you cannot do this
print_r((array)$data["id"]);
try instead
$d = (array)$data;
print_r($d["id"]);
json_decode
returns an object with the properties, not an array.
http://uk3.php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Pass true (bool value) to the second parameter in the json_decode function to get an associative array back. Then you will be able to access it as an array.
Alternatively, you could access the properties using the ->
operator.
So in your case:
print_r($data->id);
Using json_decode returns an object (eg. $data->id).
If you want it to return an array, use json_decode($data, true);