I have the following array in PHP:
Array
(
[0] => Array
(
[id] => 0
[name] => name1
[short_name] => n1
)
[2] => Array
(
[id] => 2
[name] => name2
[short_name] => n2
)
)
I want to JSON encode it as a JSON array, producing a string like the following:
[{"id":0, "name":"name1", "short_name":"n1"},{"id":2, "name":"name2", "short_name":"n2"}]
But when I call json_encode
on this array, I get the following:
{
"0":{"id":0, "name":"name1", "short_name":"n1"},
"2":{"id":2, "name":"name2", "short_name":"n2"}
}
which is an object instead of an array.
How can I get json_encode
to encode my array as an array, instead?
EDIT:
I want to use the following array with knockout.js
Array
(
[0] => Array
(
[id] => 0
[name] => name1
[short_name] => n1
)
[2] => Array
(
[id] => 2
[name] => name2
[short_name] => n2
)
)
and i am unable to loop.
Edit:
after your help i figured out my array wasn't sequential which resulted in an object instead of an array,
Array
(
[0] => Array
(
[id] => 0
[name] => name1
[short_name] => n1
)
[2] => Array
(
[id] => 2
[name] => name2
[short_name] => n2
)
)
the following works,
Array
(
[0] => Array
(
[id] => 0
[name] => name1
[short_name] => n1
)
[1] => Array
(
[id] => 2
[name] => name2
[short_name] => n2
)
)
I could achieve it finally here http://jsfiddle.net/vZdJz/4/
Thanks for all your help guys!!!
["id":0, "name":"name1", "short_name":"n1"]
is not valid JSON. Neither is{0:
. – cdhowie Jun 25 '12 at 19:09[["id":0, "name":"name1", "short_name":"n1"],["id":1, "name":"name2", "short_name":"n2"]]
should be theorically possible according to the norm, no ? – dystroy Jun 25 '12 at 19:10[{"id":0, "name":"name1", "short_name":"n1"},{"id":1, "name":"name2", "short_name":"n2"}]
would be valid. – cdhowie Jun 25 '12 at 19:12