Alaa Agwa
Alaa Agwa

Reputation: 162

php json_encode() output changes based on the array indices

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 ?

Upvotes: 2

Views: 932

Answers (1)

Amber
Amber

Reputation: 526573

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.

Upvotes: 4

Related Questions