开发者

JSON and PHP arrays

开发者 https://www.devze.com 2023-04-03 23:56 出处:网络
json_encode(array( array(0 => \"431.940054495913\"), array(1 => \"431.940054495913\"), )); Is rendered like this:
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 objects

    json_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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号