如何将 PHP 数组编码为 JSON 数组,而不是对象?
我正在尝试对从 Zend_DB 查询返回的数组进行 json_encode.
I am trying to json_encode an array which is returned from a Zend_DB query.
var_dump 给出:(手动添加 0 个成员不会改变图片.)
var_dump gives: (Manually adding 0 member does not change the picture.)
array(3) {
[1]=>
array(3) {
["comment_id"]=>
string(1) "1"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[2]=>
array(3) {
["comment_id"]=>
string(1) "2"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[3]=>
array(3) {
["comment_id"]=>
string(1) "3"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "jhghjg"
}
}
编码后的字符串如下所示:
The encoded string looks like:
{"1":{"comment_id":"1","erasable":"1","comment":"test 1"},
"2":{"comment_id":"2","erasable":"1","comment":"test 1"},
"3":{"comment_id":"3","erasable":"1","comment":"jhghjg"}}
我需要的是:
[{"comment_id":"1","erasable":"1","comment":"test 1"},
{"comment_id":"2","erasable":"1","comment":"test 1"},
{"comment_id":"3","erasable":"1","comment":"jhghjg"}]
php.ini/json_encode 文档说它应该是什么样子.
Which is what the php.ini/json_encode documentation says it should look like.
推荐答案
您如何设置初始数组?
如果你这样设置:
array(
"1" => array(...),
"2" => array(...),
);
那么你没有一个带有数字索引的数组,而是字符串,在 JS 世界中它被转换为一个对象.如果您没有设置严格的顺序(即从 0 而不是 1 开始),也会发生这种情况.
then you don't have an array with numeric indexes but strings, and that's converted to an object in JS world. This can happen also if you don't set a strict order (i.e. starting at 0 instead of 1).
然而,这是在黑暗中拍摄,因为我看不到您的原始代码:首先尝试在不使用键的情况下设置您的数组:
This is a shot in the dark, however, because I can't see your original code: try setting your array without using keys at all in the first place:
array(
array(...),
array(...),
);
相关文章