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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:10:19