0

私は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);
 ); 
4

2 に答える 2

2

このようなもの:

$result = DB::query('SELECT id, event, YEAR(event) AS event_year FROM events');
$events = array();
while($event = $result->fetch_object()) {
  $event_year = $event->event_year;
  unset($event->event_year);
  $events[$event_year][] = $event;
}

return array(
  'events' => json_encode($events, JSON_FORCE_OBJECT); // If you need it...
); 
于 2012-05-30T09:12:34.077 に答える
1

このMySQLクエリを試してください-

SELECT CONCAT('{"events":[\r\n', GROUP_CONCAT(json SEPARATOR '\r\n'), '\r\n}]}') FROM (
  SELECT
    GROUP_CONCAT(CONCAT('{"', YEAR(event), '": {"id":', id, ',"event":', event, '}}')) json
  FROM
    events1
  GROUP BY
    YEAR(event)
  ) t

次のJSON文字列を生成します-

{"events":[
{"2010": {"id":1,"event":2010-01-01 00:00:00}},{"2010": {"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}},{"2012": {"id":6,"event":2012-02-15 00:00:00}},{"2012": {"id":7,"event":2012-03-16 00:00:00}},{"2012": {"id":8,"event":2012-04-10 00:00:00}}
}]}
于 2012-05-30T09:23:46.850 に答える