JSON and PHP arrays
json_encode(array(
array(0 => "431.940054495913"),
array(1 => "431.940054495913"),
));
Is rendered like this:
[
["431.940054495913"],
{"1":"431.940054495913"}
]
Why are the two arrays 开发者_如何转开发rendered differently ?
Any PHP array that can be rendered as a JSON array will be rendered as a JSON array: Any PHP array having only sequential numeric keys starting from 0 will be rendered as a JSON array.
This is the case for the first array: array(0 => "431.940054495913")
.
How to fix this
The
JSON_FORCE_OBJECT
flag will render all PHP arrays as JSON objectsjson_encode(array(0 => "431.940054495913"), JSON_FORCE_OBJECT); // {"0": "431.940054495913"} json_encode(array(0 => "431.940054495913")); // ["431.940054495913"]
Alternatively, you could convert your PHP array to a PHP object:
json_encode( (object) array(0 => "431.940054495913")); // {"0": "431.940054495913"}
(if you don't want to render every array as object or if you don't have JSON_FORCE_OBJECT)
精彩评论