Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with json_encode()

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" }?

like image 866
cupakob Avatar asked Oct 04 '09 08:10

cupakob


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is the difference between json_encode and Json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What is json_encode in Javascript?

json_encode(mixed $value , int $flags = 0, int $depth = 512): string|false. Returns a string containing the JSON representation of the supplied value . If the parameter is an array or object, it will be serialized recursively.


2 Answers

"{}" 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.

like image 141
Maiku Mori Avatar answered Oct 31 '22 15:10

Maiku Mori


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.

like image 40
chelmertz Avatar answered Oct 31 '22 16:10

chelmertz