我试图从MySQL数据库中获得一些值,当使用json_encode()转换为JSON数组时,我得到了一个JSON对象,过了一会儿我发现索引是问题的根本原因
这是我提到的例子
<?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"]
?>
那么原因是什么呢?
因为array(0=>"zero",1=>"one")
与array("zero", "one")
相同,JSON编码器假设后者是一个列表(因为PHP就是这样做列表的),并且没有办法区分前者和后者。
如果您想强制json_encode
将所有数组视为对象,则传递JSON_FORCE_OBJECT
作为第二个参数:
json_encode(array(0=>"zero",1=>"one"), JSON_FORCE_OBJECT)
// {"0":"zero","1":"one"}
如果你总是想要一个json列表,在编码之前去掉键(例如使用array_values()
)。