我有一个 mysql 表:events
并且想获得特殊格式的 json_string。
id event
1 2010-01-01 00:00:00
2 2010-02-02 00:00:00
4 2011-01-04 00:00:00
5 2012-01-30 00:00:00
6 2012-02-15 00:00:00
7 2012-03-16 00:00:00
8 2012-04-10 00:00:00
...
我需要获取 json 字符串:
{"events":[
{"2010":{"id":1,"event":2010-01-01 00:00:00},{"id":2,"event":2010-02-02 00:00:00}},
{"2011":{"id":4,"event":2011-01-04 00:00:00}},
{"2012":{"id":5,"event":2012-01-30 00:00:00},{"id":6,"event":2012-02-15 00:00:00},{"id":7,"event":2012-03-16 00:00:00},{"id":8,"event":2012-04-10 00:00:00}}
}]}
我的代码如下:
$result = DB::query('SELECT id, event FROM events');
$events = array();
while($event = $result->fetch_object()) {
$events[] = $event;
}
return array(
'events' => json_encode($events);
);