laravel -查询近7月走势图案例

// 获取7月前的时间
$time = date('Y-m',strtotime("-0 year -7 month -0 day" ));
$where['created_at'] = ['>', $time];

// 统计近7月数据
$trend = DB::table('service_orders')
->select(DB::raw('CONCAT(YEAR(created_at),"-",MONTH(created_at)) as day'), DB::raw('sum(pay_price) as price'))
->wheres($where)
->groupBy('day')
->get()
->map(function ($value) {
return (array)$value;
})->toArray();

// 查询近7月的所有年月份
$day = 7 ;
for ($i = $day - 1; 0 <= $i; $i--) {
$result[] = date('Y-n', strtotime('-' . $i . ' month'));
$nums[] = 0;
}

// 匹配数据并返回
array_walk($trend, function ($value, $key) use ($result, &$nums) {
$index = array_search($value['day'],$result);
$nums[$index] = $value['price'];
});

$year = $result;
// 处理返回的时间格式
foreach ($year as &$v) {
$v = date('n', strtotime($v)) . '月';
}

// 返回7月走势数据
$list['trend'] = [
'month' => $year,
'price' => $nums,
'year' => $result,
];

// 返回数据
returnJson($list);

// 走势图


原文地址:https://www.cnblogs.com/jiaoda/p/10334387.html