hyclrs
hyclrs

Reputation: 33

Combine two arrays but add Values of duplicate keys together

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.

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

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

Upvotes: 2

Views: 2127

Answers (2)

Peter van der Wal
Peter van der Wal

Reputation: 11796

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;
}

Upvotes: 1

splash58
splash58

Reputation: 26153

$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);

Upvotes: 5

Related Questions