2

I was trying to get some values from MySQL database and when converting into JSON array using json_encode() I got a JSON object , after a while I found out that the indices was the root cause of the problem

here's the example I mentioned

<?php
$array = array(0=>"zero",2=>"two");
$another_array=array(0=>"zero",1=>"one");

print_r(json_encode($array)); // output: {"0":"zero","2":"two"}
print_r(json_encode($another_array)); //output: ["zero","one"]
?>

so what's the reason for that ?

1 Answer 1

4

Because array(0=>"zero",1=>"one") is the same as array("zero", "one") and the JSON encoder assumes the latter is a list (since that's how PHP does lists) and has no way to tell the former from the latter.

If you want to force json_encode to treat all arrays as objects, pass JSON_FORCE_OBJECT as the second argument:

json_encode(array(0=>"zero",1=>"one"), JSON_FORCE_OBJECT)
// {"0":"zero","1":"one"}

If you always want a json list instead, get rid of the keys (e.g. using array_values()) before encoding.

2
  • and what about array(0=>"zero",2=>"two") ? Commented May 23, 2014 at 5:06
  • 2
    That doesn't have contiguous-counting-up-from-zero indices, and thus gets treated as an object no matter what because it can't be a list. Commented May 23, 2014 at 5:07

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.