这是我们要实现的数据格式 当月每天的数据量
返回的数据格式
key 号数: value 值
"1": 1,
"2": 0,
"3": 0,
"4": 0,
"5": 1,
"6": 2,
"7": 0,
"8": 0,
"9": 0,
"10": 0,
"11": 0,
"12": 0,
"13": 0,
"14": 0,
"15": 0,
"16": 0,
"17": 0,
"18": 0,
"19": 0,
"20": 0,
"21": 0,
"22": 0,
"23": 0,
"24": 0,
"25": 0,
"26": 0,
"27": 0,
"28": 0,
"29": 0,
"30": 0,
"31": 0
数据库存的是北京时间可以下面的方法, 如果为时间戳则需要转换一下
上才艺, 北京时间写法
SELECT
date_format( created_at, '%d' ) AS `day`, # 统计日期 01 02 03 号
count(*) AS today_count # 统计当天数量
FROM
`xy_spec_route_answer`
WHERE
# 判断条件, 比如那个月的, 也可以换成当月的 下面 二选一
date_format( created_at, '%Y-%m' ) = date_format(now(), '%Y-%m') # 当月
date_format( created_at, '%Y-%m' ) = '2022-07' # 筛选月份
GROUP BY
`day` # 根据统计日期排序
上才艺, 时间戳转换写法
SELECT
date_format( created_at, '%d' ) AS `day`, # 统计日期 01 02 03 号
count(*) AS today_count # 统计当天数量
FROM
`xy_spec_route_answer`
WHERE
# 判断条件, 比如那个月的, 也可以换成当月的 下面 二选一
date_format( created_at, FROM_UNIXTIME(created_at, '%Y-%m') ) = date_format(now(), '%Y-%m') # 当月
date_format( created_at, FROM_UNIXTIME(created_at, '%Y-%m') ) = '2022-07' # 筛选月份
GROUP BY
`day` # 根据统计日期排序
PHP逻辑代码
// TP6 数据查询
$number = Db::name('spec_route_answer')->field("date_format(created_at, '%e') AS `day`, count(*) AS today_count")->where("date_format(created_at , '%Y-%m') = date_format(now(), '%Y-%m')")->group('day')->select()->toArray();
// 将数据库中取到号数, 单独抽离出来
$resDay = array_column($number, 'day');
// 计算当月天数
$day = intval(date("t",strtotime($data['time'])));
// 判断号数是否存在
$newInCount = [];
for ($i = $day; $i >= 1; $i--) {
// array_search 数组中搜索给定的值,如果成功则返回首个相应的键名
$inIndex = array_search($i, $resDay);
if ($inIndex !== false) {
// 获取数据对应的 key
$index = $number[$inIndex];
$newInCount[$i] = [
'day' => $i,
'count' => $index['today_count']
];
} else {
$newInCount[$i] = [
'day' => $i,
'count' => 0
];
}
}
// 重组一维数组
$newCount = [];
foreach ($newInCount as $v) {
$newCount[$v['day']] = $v['count'];
}
// key 排序
ksort($newCount);
dd($newCount);
就能实现下图的数据结构了
可接任何单. 如有疑问可+v: Ycc-singer , 携手开创属于自己的世界
创作不已, 三键容易, (づ ̄3 ̄)づ╭❤~