給定二維陣列,依特定鍵(如 group_id)分組,數值欄位求和:
$data = [
['group_id' => 13, 'team_price' => 88.00, 'satopay_price' => 85.00, 'quantity' => 5],
['group_id' => 13, 'team_price' => 12.00, 'satopay_price' => 11.00, 'quantity' => 3],
['group_id' => 14, 'team_price' => 4.99, 'satopay_price' => 4.60, 'quantity' => 1],
['group_id' => 14, 'team_price' => 12.00, 'satopay_price' => 11.00, 'quantity' => 2],
['group_id' => 15, 'team_price' => 13.00, 'satopay_price' => 11.00, 'quantity' => 2],
];
function groupSum(array $row, array &$result, string $groupKey): void {
// 尋找現有分組
$foundIdx = null;
foreach ($result as $idx => $group) {
if ($group[$groupKey] === $row[$groupKey]) {
$foundIdx = $idx;
break;
}
}
if ($foundIdx !== null) {
// 既有分組:數值欄位累加
foreach ($row as $key => $value) {
if ($key !== $groupKey && is_numeric($value)) {
$result[$foundIdx][$key] += $value;
}
}
} else {
// 新分組:直接加入
$result[] = $row;
}
}
$result = [];
foreach ($data as $row) {
groupSum($row, $result, 'group_id');
}
print_r($result);
[
['group_id' => 13, 'team_price' => 100.00, 'satopay_price' => 96.00, 'quantity' => 8],
['group_id' => 14, 'team_price' => 16.99, 'satopay_price' => 15.60, 'quantity' => 3],
['group_id' => 15, 'team_price' => 13.00, 'satopay_price' => 11.00, 'quantity' => 2],
]
function groupSumOptimized(array $row, array &$result, string $groupKey): void {
$groupVal = $row[$groupKey];
if (!isset($result[$groupVal])) {
$result[$groupVal] = $row;
return;
}
foreach ($row as $key => $value) {
if ($key !== $groupKey && is_numeric($value)) {
$result[$groupVal][$key] += $value;
}
}
}
// 使用時以 group_id 為索引
$result = [];
foreach ($data as $row) {
groupSumOptimized($row, $result, 'group_id');
}
// 如需連續索引:$result = array_values($result);
若資料源自資料庫,優先用 SQL 分組:
SELECT group_id,
SUM(team_price) as team_price,
SUM(satopay_price) as satopay_price,
SUM(quantity) as quantity
FROM orders
GROUP BY group_id
資料庫引擎優化程度遠高於 PHP 迴圈,大量資料務必下推至 SQL 層處理。