doumen5491 2016-09-27 00:47
浏览 199
已采纳

查询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 2016-09-27 00:56
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题