json_encode"索引数组"强制转化成"对象"
浏览量:393
why:
how:
PHP支持两种数组,一种是只保存"值"(value)的索引数组(indexed array),另一种是保存"名值对"(name/value)的关联数组(associative array)。
由于javascript不支持关联数组,所以json_encode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。
比如,现在有一个索引数组
$arr = Array("one", "two", "three");
echo json_encode($arr);
输出
["one","two","three"]
如果将它改为关联数组:
$arr = Array("1"=>"one", "2"=>"two", "3"=>"three");
echo json_encode($arr);
输出变为
{"1":"one","2":"two","3":"three"}
注意,数据格式从"[]"(数组)变成了"{}"(对象)。
如果你需要将"索引数组"强制转化成"对象",可以这样写
json_encode( (object)$arr );
或者
json_encode ( $arr, JSON_FORCE_OBJECT );


感谢支持与鼓励~