二维数组上的json_encode

时间:2009-11-03 15:10:16

标签: php arrays json

我在使用JSON和数组时遇到问题。

这是我的代码:

while($row = mysql_fetch_assoc($result)){ echo json_encode($row); }

结果是:

{"id":"1","title":"event1","start":"2009-11-10 14:18:15","end":"2009-11-03 14:38:22","allDay":"false","url":null}{"id":"2","title":"event2","start":"2009-11-09 15:41:20","end":"2009-11-10 16:41:25","allDay":"false","url":null}

但我希望结果看起来像这样:

[{"id":"1","title":"event1","start":"2009-11-10 14:18:15","end":"2009-11-03 14:38:22","allDay":"false","url":null},{"id":"2","title":"event2","start":"2009-11-09 15:41:20","end":"2009-11-10 16:41:25","allDay":"false","url":null}]

我该如何做到这一点?

2 个答案:

答案 0 :(得分:8)

$arr = array();
while($row = mysql_fetch_assoc($result)) {
    $arr[] = $row; 
}
echo json_encode($arr);

答案 1 :(得分:0)

$myjsons = array();
while($row = mysql_fetch_assoc($result)){ 
    $myjsons[] = json_encode(array($row)); 
}
print_r($myjsons);