以今天2023-09-14为例,这一周为2023-09-11~2023-09-07
运行结果
结果:
代码
后端thinkphp:
//查询本周每天的的总金额数
//获取本周的起始日期和结束日期
$weekStart = date('Y-m-d', strtotime('this week Monday'));
$weekEnd = date('Y-m-d', strtotime('this week Sunday'));
// 构造日期范围数组(从周一到周天)
$dateRange = [];
$currentDate = $weekStart;
while ($currentDate <= $weekEnd) {
$dateRange[] = $currentDate;
$currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
}
// 查询每天的总金额数
$result = Db::table('so_headers_all')
->field("DATE_FORMAT(FROM_UNIXTIME(creation_date), '%Y-%m-%d') AS date, IFNULL(SUM(order_all_amount), 0) AS total_amount")
->whereTime('creation_date', '>=', $weekStart)
->whereTime('creation_date', '<=', $weekEnd)
->group('date')
->select();
// 构造最终结果数组
$resultArray = [];
foreach ($dateRange as $date) {
$found = false;
foreach ($result as $row) {
if ($row['date'] == $date) {
$resultArray[] = $row;
$found = true;
break;
}
}
if (!$found) {
$resultArray[] = ['date' => $date, 'total_amount' => 0];
}
}
$data['week_info'] = $resultArray;
扩展:增加星期
结果
代码
后端thinkphp:
//查询本周每天的的总金额数
//获取本周的起始日期和结束日期
$weekStart = date('Y-m-d', strtotime('this week Monday'));
$weekEnd = date('Y-m-d', strtotime('this week Sunday'));
// 构造日期范围数组(从周一到周天)
$dateRange = [];
$currentDate = $weekStart;
while ($currentDate <= $weekEnd) {
$dateRange[] = $currentDate;
$currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
}
// 查询每天的总金额数
$result = Db::table('so_headers_all')
->field("DATE_FORMAT(FROM_UNIXTIME(creation_date), '%Y-%m-%d') AS date, IFNULL(SUM(order_all_amount), 0) AS total_amount")
->whereTime('creation_date', '>=', $weekStart)
->whereTime('creation_date', '<=', $weekEnd)
->group('date')
->select();
//去掉逗号,转换为
foreach ($result as &$item) {
// $item['total_amount'] = intval(($item['total_amount'] / 10000));
$item['total_amount'] = round(($item['total_amount'] / 10000),2);
}
// 构造最终结果数组
$resultArray = [];
$dateArray = [];
$totalAmountArray = [];
$weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
foreach ($dateRange as $date) {
$found = false;
foreach ($result as $row) {
if ($row['date'] == $date) {
$weekdayIndex = date('w', strtotime($row['date']));
$row['name'] = $weekdays[$weekdayIndex];
$resultArray[] = $row;
$dateArray[] = $row['date'];
$totalAmountArray[] = $row['total_amount'];
$found = true;
break;
}
}
if (!$found) {
$weekdayIndex = date('w', strtotime($date));
$resultArray[] = ['date' => $date, 'total_amount' => 0, 'name' => $weekdays[$weekdayIndex]];
$dateArray[] = $date;
$totalAmountArray[] = 0;
}
}
$data['week_info']['date'] = $dateArray;
$data['week_info']['total_amount'] = $totalAmountArray;
$data['week_info1'] = $resultArray;
echo json_encode($data);