Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 856
Fuzzy Avatar asked Sep 08 '11 11:09

Fuzzy


1 Answers

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)

like image 51
Arnaud Le Blanc Avatar answered Oct 25 '22 07:10

Arnaud Le Blanc