14
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 ?

2
  • Difficult to understand what is being asked. Everything looks normal to me. Commented Sep 8, 2011 at 11:10
  • He wants to know why the elements with key '0' and key '1' are different when converted to JSON Commented Sep 8, 2011 at 11:12

1 Answer 1

17

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Tried both and they both fix the issue. Good to know :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.