SUN Jiangong
SUN Jiangong

Reputation: 5312

json_encode on a two-dimensional array

I have a problem using JSON and arrays.

Here is my code:

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

The result is:

{"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}

But I want the result to look like this:

[{"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}]

How can I accomplish this?

Upvotes: 3

Views: 16712

Answers (2)

brettkelly
brettkelly

Reputation: 28215

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

Upvotes: 0

viam0Zah
viam0Zah

Reputation: 26312

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

Upvotes: 8

Related Questions