問題描述
我正在嘗試對從 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(...),
);
這篇關于如何將 PHP 數組編碼為 JSON 數組,而不是對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!