views:

1178

answers:

3

Hi all,

i have an simple array:

array
  0 => string 'Kum' (length=3)
  1 => string 'Kumpel' (length=6)

when I encode the array using json_encode(), i get following:

["Kum","Kumpel"]

My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?

+6  A: 

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.

$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}

The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.

Note: according to PHP manual the options parameters are only available from PHP 5.3.

*For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.*

Maiku Mori
not exactly, i get this warning:Warning: json_encode() expects exactly 1 parameter, 2 given..
cupakob
That's strange, it's copy-paste from manual.
Maiku Mori
"5.3.0 The options parameter was added."
VolkerK
VolkerK, thanks. It's been quite some time since I last used php, but I think I had some beta version of 5.3 back then, because I remember using those option parameters.
Maiku Mori
A: 

Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.

Gumbo
+2  A: 

As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:

$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);

Not that usable, I'd stick with the array notation.

chelmertz