-4
$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?

Clem
  • 11,334
  • 8
  • 34
  • 48
  • 7
    With `json_decode($data)`, you'll be getting an object. To get an associative array, set the second parameter as `TRUE`. See the [documentation for `json_decode()`](http://php.net/json_decode) for more information. – Amal Murali May 12 '14 at 12:55
  • 2
    The output shown in your question isn't correct either. The second statement would print out an error "*Fatal error: Cannot use object of type stdClass as array*". ([Enable error reporting](http://stackoverflow.com/a/6575502/1438393) if you haven't already.) – Amal Murali May 12 '14 at 12:56
  • 1
    Use `var_dump` in order to get info about type structure you are dealing with. – moonwave99 May 12 '14 at 12:59
  • Ok I understand now. I have object but I tried to use it like array. Thanks for help and -1. – Clem May 12 '14 at 13:04

4 Answers4

3
(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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    @deceze , isn't this a bit too complicated question for 200k user? Maybe you should stick with "missing semicolon" questions for now. – tereško May 12 '14 at 13:02
  • @tereško Yeah, feeling a bit out of my depth here... ^_^;; But who else was going to deliver this explanation...? – deceze May 12 '14 at 13:31
1

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);
DarkMantis
  • 1,510
  • 5
  • 19
  • 40
0

you cannot do this

print_r((array)$data["id"]);

try instead

$d = (array)$data;
print_r($d["id"]);
i100
  • 4,529
  • 1
  • 22
  • 20
0

Using json_decode returns an object (eg. $data->id).
If you want it to return an array, use json_decode($data, true);

PavKR
  • 1,591
  • 2
  • 11
  • 26