JSON_ENCODE for multidimensional array giving different results
arrays, json, php
Solution
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}}
Problem
When using json_encode for a multidimensional array in PHP, I'm noticing an output when naming one of the arrays, but different output when I am not naming them. For Example: ``` $arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4)); json_encode($arrytest) ``` gives a single array of multiple json objects ``` [{"a":1,"b":2},{"c":3},{"d":4}]; ``` whereas simply assigning a name to the middle array ``` $arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4)); json_encode($arrytest) ``` creates a single json object with multiple json objects inside ``` {"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}}; ``` why would the 1st option not return the same reasults like the 2nd except with "1" in place of "secondarray"