You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Laravel查询结果提取为数组?现有代码需调整

解决Laravel中日期统计数组的常见修改需求

你已经通过这段Laravel代码成功提取了每日匹配数的数组,但既然你提到需要修改,我整理了几个常见场景的优化方案,你可以根据实际需求参考:


场景1:补全日期范围内的所有日期(含无匹配日期填充0)

默认查询只会返回有匹配记录的日期,如果需要展示连续日期(比如近7天),即使当天没有匹配也要显示0,可以这样调整:

// 定义日期范围,示例为最近7天
$startDate = Carbon::now()->subDays(6)->startOfDay();
$endDate = Carbon::now()->endOfDay();

// 生成连续的日期数组
$dates = [];
$currentDate = $startDate->copy();
while ($currentDate <= $endDate) {
    $dates[] = $currentDate->format('Y-m-d');
    $currentDate->addDay();
}

// 执行原查询并转为「日期-数量」的关联数组
$matchCounts = DiraChatLog::where('status', 'Match')
    ->selectRaw('DATE(created_at) as date, COUNT(1) as cnt')
    ->whereBetween('created_at', [$startDate, $endDate])
    ->orderBy('date')
    ->groupBy('date')
    ->pluck('cnt', 'date')
    ->toArray();

// 遍历连续日期,补全无匹配日期的0值
$result = array_map(function ($date) use ($matchCounts) {
    return $matchCounts[$date] ?? 0;
}, $dates);

最终$result会是包含连续日期对应数量的数组,无匹配的日期自动填充0。


场景2:同时保留日期和数量的关联数组

如果你需要同时获取日期和对应的数量(而非仅数量的索引数组),可以简化代码:

$match = DiraChatLog::where('status', '=', 'Match')
    ->selectRaw('DATE(created_at) as date, COUNT(1) as cnt')
    ->orderBy("date")
    ->groupBy("date")
    ->get()
    ->toArray();

返回的数组结构为:

[
    ['date' => '2024-05-01', 'cnt' => 5],
    ['date' => '2024-05-02', 'cnt' => 3],
    // ...
]

场景3:修改统计维度为周/月

如果需要按周或月统计,只需调整selectRaw和groupBy的字段:

按周统计

$match = DiraChatLog::where('status', '=', 'Match')
    ->selectRaw('YEARWEEK(created_at) as week, COUNT(1) as cnt')
    ->orderBy("week")
    ->groupBy("week")
    ->get()
    ->pluck('cnt')
    ->values()
    ->all();

按月统计

$match = DiraChatLog::where('status', '=', 'Match')
    ->selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, COUNT(1) as cnt')
    ->orderBy("month")
    ->groupBy("month")
    ->get()
    ->pluck('cnt')
    ->values()
    ->all();

场景4:添加额外筛选条件

如果需要按用户类型、时间段等条件筛选,只需在查询中追加where子句:

$match = DiraChatLog::where('status', '=', 'Match')
    ->where('user_type', 'customer') // 新增筛选用户类型
    ->whereTime('created_at', '>=', '09:00:00') // 筛选当天9点后的记录
    ->selectRaw('DATE(created_at) as date, COUNT(1) as cnt')
    ->orderBy("date")
    ->groupBy("date")
    ->get()
    ->pluck('cnt')
    ->values()
    ->all();

如果你的修改需求不在以上场景里,可以补充说明具体需求(比如调整返回格式、处理时区、聚合方式等),我再帮你针对性调整代码~

内容的提问来源于stack exchange,提问作者Rajveer Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:34:36