JSON_ENCODE of multidimensional array giving different results

In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.

If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.

$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));

// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);

// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}

Arrays with continuous numerical keys are encoded as JSON arrays. That's just how it is. Why? Because it makes sense.

Since the keys can be expressed implicitly through the array encoding, there is no reason to explicitly encoded them as object keys.

See all the examples in the json_encode documentation.


At the first option you only have numeric indexes (0, 1 and 2). Although they are not explicitly declared, php automatically creates them.

At the second option, you declare one of the indexes as an string and this makes PHP internally transform all indexes to string.

When you json encode the first array, it's not necessary to show the integers in the generated json string because any decoder should be able to "guess" that they are 0, 1 and 2.

But in the second array, this is necessary, as the decoder must know the key value in your array.

It's pretty simple. No indexes declared in array? Them they are 0, 1, 2, 3 and so on.

Tags:

Php

Arrays

Json