本文详解如何基于订单数据,按商品 id、sku、变体和规格维度精准聚合销售次数,提供可直接运行的 php 数组计数方案及 laravel 数据库查询优化建议。
在电商系统中,同一商品常存在多个变体(如口味、颜色)和规格(如 1KG、340g),而业务需求往往要求统计「每个具体组合(ID + Variant + Size)的销售频次」,而非简单去重或全局计数。原始代码仅实现了重复项计数与基础去重,未建立多维键映射关系,导致无法生成带 count 字段的结构化结果。
✅ 正确思路:以复合键为唯一标识进行分组聚合
核心在于将 productID、variant 和 size(或更佳实践:productID + SKU + variant + size)共同构成哈希键,用关联数组实现 O(1) 查找与累加。避免嵌套循环遍历(如原答案中低效的 for 搜索),推荐使用 字符串拼接键 或 序列化键 提升性能与可读性。
以下是优化后的 PHP 实现(兼容 PHP 7.4+,含注释与健壮性处理):
select('product_id as productID', 'sku as SKU', 'variant', 'size')
->whereBetween('created_at', [$date['start'], $date['end']])
->where('status', 'completed') // 建议过滤有效订单
->get()
->toArray();
// 使用关联数组按复合键聚合计数
$result = [];
foreach ($orders as $order) {
// 构建唯一键:确保字段非空,防止 null 导致键冲突
$key = sprintf('%s_%s_%s_%s',
$order->productID ?? 0,
$order->SKU ?? '',
$order->variant ?? '',
$order->size ?? ''
);
if (!isset($result[$key])) {
$result[$key] = [
'productID' => $order->productID,
'SKU' => $order->SKU,
'variant' => $order->variant,
'size' => $order->size,
'count' => 0
];
}
$result[$key]['count']++;
}
// 转为索引数组并保持顺序(可选:按 count 降序排列)
$finalResult = array_values($result);
usort($finalResult, fn($a, $b) => $b['count'] $a['count']);
print_r($finalResult);
?>
? 输出示例(匹配题目期望格式)
Array (
[0] => Array ( [productID] => 1089 [SKU] => 123 [variant] => A [size] => 1KG [count] => 2 )
[1] => Array ( [productID] => 1090 [SKU] => 124 [variant] => C [size] => 1KG [count] => 3 )
[2] => Array ( [productID] => 1089 [SKU] => 123 [variant] => B [size] => 250gm [count] => 1 )
// ... 其他条目
)
⚠️ 关键注意事项
-
数据库层优先聚合:若数据量大(>10k 行),强烈建议改用 SQL GROUP BY 直接计算,减少 PHP 内存压力:
SELECT product_id AS productID, sku AS SKU, variant, size, COUNT(*) AS count FROM orders WHERE created_at BETWEEN ? AND ? AND status = 'completed' GROUP BY product_id, sku, variant, size ORDER BY count DESC;对应 Laravel 查询: