合并两个数组,但同时添加重复键的值

时间:2022-09-05 19:15:17

I have two arrays, $ids and $quants (ids and quantities of stock items) that need to be combined, but instead of replacing or removing duplicates, their values should be added together.

我有两个数组,$id和$quant (id和股票项目的数量)需要合并,但是与其替换或删除重复,不如将它们的值相加。

Currently I'm using array_combine() but this means that some of the quantities are lost where multiple of the same id exists.

目前我正在使用array_combine(),但这意味着当存在多个相同id时,会丢失一些数量。

e.g.

如。

$ids = Array(1, 1, 2, 3);
$quants = Array(10, 20, 30, 40);

Desired output:

期望的输出:

$combined = Array(
[1] => 30
[2] => 30
[3] => 40
)

Thanks in advance for any advice

谢谢你的建议

2 个解决方案

#1


4  

$ids = Array(1, 1, 2, 3);
$quants = Array(10, 20, 30, 40);

$a = array_unique($ids);
$a = array_combine($a, array_fill(0, count($a), 0));

foreach($ids as $k=>$v) {
  $a[$v] += $quants[$k];
}

print_r($a);

#2


1  

There isn't a built in function, so you have to do it yourself:

没有内置的功能,所以你必须自己做:

function my_array_combine($keys, $values)
{   
    if (count($keys) != count($values)) {
        throw new InvalidArgumentException('More or less');
    } 

    $result = array();

    $values = array_values($values); // make sure it is indexed 0, 1, 2
    foreach(array_values($keys) as $idx => $key) {
        // Correspondending value is at $values[$idx];
        if (isset($result[$key])) {
            $result[$key] += $values[$idx];
        } else {
            $result[$key] = $values[$idx];
        }
    }

    return $result;
}

#1


4  

$ids = Array(1, 1, 2, 3);
$quants = Array(10, 20, 30, 40);

$a = array_unique($ids);
$a = array_combine($a, array_fill(0, count($a), 0));

foreach($ids as $k=>$v) {
  $a[$v] += $quants[$k];
}

print_r($a);

#2


1  

There isn't a built in function, so you have to do it yourself:

没有内置的功能,所以你必须自己做:

function my_array_combine($keys, $values)
{   
    if (count($keys) != count($values)) {
        throw new InvalidArgumentException('More or less');
    } 

    $result = array();

    $values = array_values($values); // make sure it is indexed 0, 1, 2
    foreach(array_values($keys) as $idx => $key) {
        // Correspondending value is at $values[$idx];
        if (isset($result[$key])) {
            $result[$key] += $values[$idx];
        } else {
            $result[$key] = $values[$idx];
        }
    }

    return $result;
}