I discovered the other day that I json_encode was converting php arrays into json and sometimes, but sometimes not, adding indexes to elements.
$array1 = array(
'first',
array('second'=> 'third',
'fourth' => 'fifth'
),
arrays('sixth' => 'seventh'),
);
var_dump(json_encode($array1)); // output: '["first",{"second":"third","fourth":"fifth"},{"sixth":"seventh"}]'
// first element in the array is now associative:
$array2 = array(
'first' => 'new value',
array('second'=> 'third',
'fourth' => 'fifth'
),
arrays('sixth' => 'seventh'),
);
var_dump(json_encode($array2)); // output: '["first":"new value',"0":{"second":"third","fourth":"fifth"},"1": {"sixth":"seventh"}]'
Can someone explain this behavior to me? I want to be able to create multidimensional arrays where the sub-arrays are not associated with a key in json, as in the first example. Whether or not json_encode gives sub arrays explicit keys appears to depend on whether the top most array in the multidimensional array has an explicitly associative element in it (‘first’ => ‘subvalue’ instead of just 'first). But that is all I could find from testing various arrays and json_encoding them.
What determines whether json_encode adds array keys or not, and can the behavior be explicitly controlled?