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

PHP中array_combine()未达预期,求合并数组并统计产品总量方案

解决PHP中合并重复键数组并统计产品总数量的问题

你用array_combine($arr_a, $arr_b)得不到预期结果的核心原因是:PHP数组的键必须唯一,重复的键会被后面的值直接覆盖,所以这个函数既没法生成你想要的重复键结构,也不符合PHP数组的特性。

要实现统计各产品总数量的目标,这里有几种实用的实现方法:

方法一:循环遍历累加(最直观)

直接遍历两个数组,以产品名称为键,逐步累加对应数量:

$arr_a = [2, 3, 10, 3, 4, 8, 5, 1, 1];
$arr_b = ["Hello world poduct", "Test Product", "Hello world poduct", "Hello world poduct", "Test Product", "Test Product", "Test Product", "Test Product", "Test Product"];

$result = [];
foreach ($arr_b as $index => $product) {
    $quantity = $arr_a[$index];
    // 已存在该产品则累加,否则初始化数量
    if (isset($result[$product])) {
        $result[$product] += $quantity;
    } else {
        $result[$product] = $quantity;
    }
}

print_r($result);

输出结果:

Array
(
    [Hello world poduct] => 15
    [Test Product] => 22
)

方法二:函数式写法(array_map + array_reduce)

通过映射生成键值对数组,再用归并操作完成累加:

$arr_a = [2, 3, 10, 3, 4, 8, 5, 1, 1];
$arr_b = ["Hello world poduct", "Test Product", "Hello world poduct", "Hello world poduct", "Test Product", "Test Product", "Test Product", "Test Product", "Test Product"];

// 把两个数组映射为单个键值对的数组集合
$pairs = array_map(function($qty, $prod) {
    return [$prod => $qty];
}, $arr_a, $arr_b);

// 归并累加数量
$result = array_reduce($pairs, function($carry, $item) {
    $prod = key($item);
    $carry[$prod] = ($carry[$prod] ?? 0) + current($item);
    return $carry;
}, []);

print_r($result);

方法三:分组后求和

先按产品名称分组存储对应数量,再对每组数量求和:

$arr_a = [2, 3, 10, 3, 4, 8, 5, 1, 1];
$arr_b = ["Hello world poduct", "Test Product", "Hello world poduct", "Hello world poduct", "Test Product", "Test Product", "Test Product", "Test Product", "Test Product"];

$grouped = [];
foreach ($arr_b as $index => $product) {
    $grouped[$product][] = $arr_a[$index];
}

// 对每组数量求和
$result = array_map('array_sum', $grouped);

print_r($result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:15:38