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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧