Reputation: 33
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
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
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