I have an array like this. it contain three array list and two are same product id here what i want to do , add both price and quantity values in the list and make that to a sing array
Array
(
[0] => Array
(
[order_product_id] => 882
[order_id] => 814
[product_id] => 192
[quantity] => 40
[price] => 410.0000
[total] => 16400.0000
[product_value] => 25
)
[1] => Array
(
[order_product_id] => 881
[order_id] => 815
[product_id] => 200
[quantity] => 20
[price] => 1049.0000
[total] => 20980
[product_value] => 60
)
[2] => Array
(
[order_product_id] => 882
[order_id] => 815
[product_id] => 192
[quantity] => 10
[price] => 410.0000
[total] => 4100.0000
[product_value] => 25
)
)
So here, I want an array like this
Array
(
[0] => Array
(
[order_product_id] => 882
[order_id] => 814
[product_id] => 192
[quantity] => 60
[price] => 410.0000
[total] => 24600.0000
[product_value] => 25
)
[1] => Array
(
[order_product_id] => 881
[order_id] => 815
[product_id] => 200
[quantity] => 20
[price] => 1049.0000
[total] => 20980
[product_value] => 60
)
)
I tried condition code like this but didn't work it properly
foreach ($product as $key => $products)
{
foreach ($product as $keys => $row)
{
if ($products['product_id']==$row['product_id'])
{
}
else
{
}
}
}
so somebody please help me to figure it out please
This should work nicely. Essentially we are giving each array a key based on the id in a new array and over each iteration we check if we've already done the previous and if so we add the price and quantity:
$array = array(
0 => array(
'order_product_id' => 882,
'quantity' => 40,
'price' => 410
),
1 => array(
'order_product_id' => 881,
'quantity' => 20,
'price' => 1049
),
2 => array(
'order_product_id' => 882,
'quantity' => 10,
'price' => 410
)
);
$mod_arr = array();
foreach ($array as $item) {
$id = $item['order_product_id'];
// we've already created this item? yes: add together current item price and quantity with previous
if (isset($mod_arr[$id])) {
$mod_arr[$id]['quantity'] = $mod_arr[$id]['quantity'] + $item['quantity'];
$mod_arr[$id]['price'] = $mod_arr[$id]['price'] + $item['price'];
continue;
}
$mod_arr[$id] = $item;
}
echo '<pre>';
print_r($mod_arr);
Generates:
Array
(
[882] => Array
(
[order_product_id] => 882
[quantity] => 50
[price] => 820
)
[881] => Array
(
[order_product_id] => 881
[quantity] => 20
[price] => 1049
)
)