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

PHP如何统计数组中相同post_id和post_type的条目总数

方案1:查询阶段直接统计(推荐)

直接在SQL查询时完成分组统计,性能最优,无需额外处理数组,代码如下:

$postStats = PostTracking::selectRaw('post_id, post_type, DATE(created_at) as created_at, COUNT(*) as total')
    ->whereDate('created_at', '2021-09-11')
    ->groupBy('post_id', 'post_type', \DB::raw('DATE(created_at)'))
    ->get()
    ->toArray();

该语句会直接返回符合你要求的数组结构,数据量越大,相比后续处理数组的方案优势越明显。

方案2:PHP层处理已有数组

如果必须基于你已经查询得到的$postList数组做二次处理,可以通过遍历分组实现:

$grouped = [];
$statisticsDate = '2021-09-11'; // 你查询限定的日期

foreach ($postList as $item) {
    // 用post_id和post_type拼接唯一分组标识
    $groupKey = $item['post_id'] . '|' . $item['post_type'];
    if (!isset($grouped[$groupKey])) {
        $grouped[$groupKey] = [
            'post_id' => $item['post_id'],
            'post_type' => $item['post_type'],
            'created_at' => $statisticsDate,
            'total' => 0
        ];
    }
    $grouped[$groupKey]['total'] += 1;
}

// 重置数组索引,得到最终结果
$result = array_values($grouped);

处理完成后$result就是你期望的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:36:02