Reputation: 3756
I have an array in the format:
array (
'1' => array (
'id' => '2',
'qty' => '4'
),
'2' => array (
'id' => '1',
'qty' => '1'
),
'3' => array (
'id' => '2',
'qty' => '3'
),
'4' => array (
'id' => '4',
'qty' => '6'
)
);
And want to find all duplicates of the column 'id', and to combine them into one (adding the values for 'qty' together).
Is there a better way to do this than a two foreach's? - it seems a bit too brute-forcey for me.
Upvotes: 2
Views: 2107
Reputation: 316999
Not pretty, but I think it does what it should (edited to maintain format):
$id = array();
foreach($array as $v) {
if( $id[$v['id']] ) {
$id[$v['id']]['qty'] += $v['qty'];
} else {
$id[$v['id']] = $v;
}
}
// Optional reset keys
// $id = array_values($id);
// Optional sort keys in ascending order
// ksort($id);
print_r($id);
Gives:
Array
(
[2] => Array
(
[id] => 2
[qty] => 7
)
[1] => Array
(
[id] => 1
[qty] => 1
)
[4] => Array
(
[id] => 4
[qty] => 6
)
)
Upvotes: 4
Reputation: 61567
You could change this a little to maintain the format, but this is basically the way to do it.
$items_by_id = array();
foreach($array as $item)
{
if(!isset($items_by_id[$item['id']]))
{
$items_by_id[$item['id']] = $item['qty'];
}
else
{
$items_by_id[$item['id']] += $item['qty'];
}
}
Upvotes: 2