PHP如何从两个对应数组统计各月份销售总额?
解决方案
方法一:直接遍历累加(最直观)
利用两个数组键一一对应的特性,直接通过索引关联月份与数值,用结果数组的键存储月份,值存储累加后的总额:
$months = ['Apr 2023', 'Mar 2023', 'Apr 2023', 'Apr 2023', 'Feb 2023']; $values = [833.00, 223.00, 829.00, 220.00, 498.00]; $totalSales = []; foreach ($months as $index => $month) { if (isset($totalSales[$month])) { $totalSales[$month] += $values[$index]; } else { $totalSales[$month] = $values[$index]; } } // 输出格式化后的结果 foreach ($totalSales as $month => $total) { echo "{$month}: " . number_format($total, 2) . "\n"; }
运行后输出:
Apr 2023: 1882.00 Mar 2023: 223.00 Feb 2023: 498.00
方法二:array_map + array_reduce 函数式实现
如果偏好函数式写法,可先将两个数组合并为包含月份和数值的关联数组列表,再用array_reduce完成累加:
$months = ['Apr 2023', 'Mar 2023', 'Apr 2023', 'Apr 2023', 'Feb 2023']; $values = [833.00, 223.00, 829.00, 220.00, 498.00]; // 合并为每个元素包含月份与数值的数组 $combined = array_map(function($month, $value) { return ['month' => $month, 'value' => $value]; }, $months, $values); // 累加计算各月份总额 $totalSales = array_reduce($combined, function($result, $item) { $month = $item['month']; // 空合并运算符处理初始值 $result[$month] = ($result[$month] ?? 0) + $item['value']; return $result; }, []); // 输出结果 foreach ($totalSales as $month => $total) { echo "{$month}: " . number_format($total, 2) . "\n"; }
关于你之前遇到的问题
- 使用
array_reduce出现类型错误,大概率是直接用array_combine合并数组导致的——array_combine不允许重复键,会直接覆盖之前的数值,造成数据丢失和类型异常。 - 无需对比遍历项与前一项,直接用月份作为结果数组的键,天然就能实现分组累加,逻辑更简洁。
内容的提问来源于stack exchange,提问作者digerati
相关产品推荐
相关产品推荐

