I'm working on a way to filter out double values, as my example below shows that the are products present in the array that are basically double and should be combined(make a new key with the values combined).
The product should be combined by api_id.
//old current array
[products] => Array
(
[product_5c7fb5f72f9d5_192] => Array
(
[record_id] => 84721
[api_id] => 192
[amount] => 12
[cost_price] => 3.36
)
[product_5c7fb5f72fe49_192] => Array
(
[record_id] => 84722
[api_id] => 177
[amount] => 1
[cost_price] => 1.09
)
[product_5c7fb5f7301b2_192] => Array
(
[record_id] => 84724
[api_id] => 192
[amount] => 24
[cost_price] => 6.72
)
[product_5c7fb5f7301b2_192] => Array
(
[record_id] => 84725
[api_id] => 192
[amount] => 24
[cost_price] => 6.72
)
)
// this should be new new array
[products] => Array
(
[product_5c7fb5f72f9d5_192] => Array
(
[record_id] => 84721
[api_id] => 192
[amount] => 60//new value
[cost_price] => 16.8//new value
)
[product_5c7fb5f72fe49_192] => Array
(
[record_id] => 84722
[api_id] => 177
[amount] => 1
[cost_price] => 1.09
)
)
You can use array_reduce
:
$products = array_reduce($products, function ($carry, $product) {
if (!isset($carry[$product['api_id']])) {
$carry[$product['api_id']] = $product;
}
else {
$carry[$product['api_id']]['amount'] += $product['amount'];
$carry[$product['api_id']]['cost_price'] += $product['cost_price'];
}
return $carry;
}, []);