I have an array that looks like the below (this is a print_r on a $data variable)
Array ( [0] => Array ( [quan] => 1 [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a [title] => Broomhandle - 6" x 12.5" [total] => 11.00 [weight] => 0.25 [image] => thumb_37658989fcd29e9.jpg ) [1] => Array ( [quan] => 1 [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a [title] => Broomhandle - 6" x 12.5" [total] => 11.00 [weight] => 0.25 [image] => thumb_37658989fcd29e9.jpg ) [2] => Array ( [quan] => 1 [prod_key] => of2ef85vb8333afaeec8cd51be30jq7i [title] => Watch [total] => 65.00 [weight] => 0.15 [image] => thumb_37658989fcd29e9.jpg ) )
What I am trying to do is loop through the array and combine the items that have the same prod_key into one item and update the the total, quantity and weight so the above example should look like:
Array ( [0] => Array ( [quan] => 2 [prod_key] => 6f2e8858b8333afaeec8cd51be30ba6a [title] => Broomhandle - 6" x 12.5" [total] => 22.00 [weight] => 0.50 [image] => thumb_37658989fcd29e9.jpg ) [1] => Array ( [quan] => 1 [prod_key] => of2ef85vb8333afaeec8cd51be30jq7i [title] => Watch [total] => 65.00 [weight] => 0.15 [image] => thumb_37658989fcd29e9.jpg ) )
make a new array and use the product key as an array indice. Then you can easily add or update the entries
$result = array();
foreach ($data as $v) {
if (!isset($result[$v['prod_key']])) {
$result[$v['prod_key']] = $v;
} else {
$result[$v['prod_key']]['quan'] += $v['quan'];
$result[$v['prod_key']]['total'] += $v['total'];
$result[$v['prod_key']]['weight'] += $v['weight'];
//etc...
}
}