php - Empty array fields cause json_encode's output type to change from JSONArray to JSONObject -
this code's output type jsonarray:
for($i=0;$i<4;++$i) { $data[$i]['name'] = 'myname'.$i; } $json = json_encode($data, json_unescaped_unicode); header('content-type: application/json; charset=utf-8'); echo $json;
result:
[{"name":"myname0"},{"name":"myname1"},{"name":"myname2"},{"name":"myname3"}]
but when skip of them, it's output type jsonobject!!!:
for($i=0;$i<4;++$i) { $data[$i]['name'] = 'myname'.$i; ++$i; } $json = json_encode($data, json_unescaped_unicode); header('content-type: application/json; charset=utf-8'); echo $json;
result:
{"0":{"name":"myname0"},"2":{"name":"myname2"}}
why?!
and can see, field numbers names objects.
when encoding array, if keys not continuous numeric sequence starting 0, keys encoded strings, , specified explicitly each key-value pair.
the 2nd example in question refers situation above. that's why result json become js object
.
Comments
Post a Comment