I am trying to json_encode an array which is returned from a Zend_DB query.
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"}}
What I need is:
[{"comment_id":"1","erasable":"1","comment":"test 1"},
{"comment_id":"2","erasable":"1","comment":"test 1"},
{"comment_id":"3","erasable":"1","comment":"jhghjg"}]
Which is what the php.ini/json_encode documentation says it should look like.
Added information that expands on Seb's answer.
Note: its formatting it this way with good cause:
If you were to send
as
When you did
$data[1]
in Php you would get back "a", but on the JavaScript side, you would get back "b" .i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:
A common way to test for a traditional, continuous array in php is to check for an index '0'. Try adding that to your array, it'll probably considering it an array instead of hashmap.
How are you setting up your initial array?
If you set it up like:
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: