doumen5491
doumen5491
2016-09-27 00:47

查询MySQL计数数据并转换为JSON

My table contains a column of 'datetimes', with an id.

+----+---------------------+
| id |      datetime       |
+----+---------------------+
| 0  | 2016-09-02 12:13:13 |
| 1  | 2016-09-02 10:16:11 |
| 2  | 2016-09-05 11:03:23 |
| 3  | 2016-09-08 11:34:45 |
| 4  | 2016-09-08 09:23:06 |
| 5  | 2016-09-08 10:22:05 |
| .. |         ...         |
+----+---------------------+

There will be multiple instances of each date in the table. My aim is to gather the amount of times each date occurs. So for the table above:

2016-09-02 => 2
2016-09-05 => 1
2016-09-08 => 3

I then need to move the data into JSON format using PHP like so:

[{"date":"2016-09-02","count":"2"},
 {"date":"2016-09-05","count":"1"},
 {"date":"2016-09-08","count":"3"}]

The JSON format will be used by a d3.js script I have written to plot each date against the frequency each date occurs.

I have never dealt with this kind of query before so I really have no idea where to start, or how to use PHP to move into JSON format. Thank you to anyone that can help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doufu7835 doufu7835 5年前

    Use the following query:

    SELECT DATE_FORMAT(datetime, '%Y-%m-%d') AS `date`,
           COUNT(*) AS `count`
    FROM yourTable
    GROUP BY DATE_FORMAT(datetime, '%Y-%m-%d')
    

    Then create the JSON in your PHP code:

    $a = array();
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $a[] = array('date' => "$row['date']", 'count' => "$row['count']");
    }
    
    $json = json_encode($a);
    
    点赞 评论 复制链接分享
  • droebnxrm31502512 droebnxrm31502512 5年前

    I think below SQL useful to you. please run and see

    SELECT  DATE_FORMAT(datetime, '%Y-%m-%d'),count(*)
    FROM yourTable
    GROUP BY 1
    order by 1
    
    点赞 评论 复制链接分享

为你推荐