为了账号安全,请及时绑定邮箱和手机立即绑定

mysql - 如何创建按天数分组的连续日期图表?

mysql - 如何创建按天数分组的连续日期图表?

PHP
守候你守候我 2021-12-03 15:00:23
我想创建一个在 x 轴上从最小日期到最大日期连续日期的图表;并每天计数。我有这张表:ID  Date      ==============1   2018-01-05    2   2018-01-053   2018-01-074   2018-01-085   2018-01-08这就是我所拥有的,但我无法获得连续的日期$sql = "SELECT date,COUNT(*) FROM table GROUP BY date";$result = $conn->query($sql);while ($row = $result->fetch_assoc()) {    $x_axis[] = $row['date'];    $values[] = $row['COUNT(*)'];}所需结果的示例是(当该中间日期没有记录时,我想得到零):2018-01-05 => 22018-01-06 => 02018-01-07 => 12018-01-08 => 2
查看完整描述

1 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

像这样做:


$finaldata = array();

$sql = "SELECT date, COUNT(*) total FROM ( SELECT * FROM Table ORDER BY date ASC) AS sub GROUP BY date";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {

    $x_axis[] = $row['date'];

    $values[] = $row['COUNT(*)'];

}


for($date = $x_axis[0]; strtotime($date) <= strtotime(end($x_axis)); ) {

    $key = array_search($date, $x_axis);

    $finaldata[$date] = $key === FALSE ? 0 : $values[$key];

    $date = date('Y-m-d', strtotime('+1 day', strtotime($date)))

}


echo "<pre>";print_r($finaldata);die;

您的最终数据在$finaldata数组中


查看完整回答
反对 回复 2021-12-03
  • 1 回答
  • 0 关注
  • 157 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信