I'm experiencing odd behavior with json_encode
after removing a numeric array key with unset
:
$a = array(
new stdclass,
new stdclass,
new stdclass
);
$a[0]->abc = '123';
$a[1]->jkl = '234';
$a[2]->nmo = '567';
printf("%s\n", json_encode($a));
unset($a[1]);
printf("%s\n", json_encode($a));
Program Output
[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}]
{"0":{"abc":"123"},"2":{"nmo":"567"}}
The first time $a
is converted to JSON, it's encoded as an array. The second time, it's encoded as an object. Why is this happening, and how can I prevent it?