I have an array that looks like this:
array:3 [
0 => array:5 [
"id" => 18
"product_id" => 37
"total_price" => "643.00"
"created_at" => "2017-05-02 13:22:35"
"updated_at" => "2017-05-02 13:22:35"
]
1 => array:5 [
"id" => 19
"product_id" => 36
"total_price" => "532.00"
"created_at" => "2017-05-02 13:23:47"
"updated_at" => "2017-05-02 13:23:47"
]
2 => array:5 [
"id" => 20
"product_id" => 36
"total_price" => "532.00"
"created_at" => "2017-05-03 13:20:47"
"updated_at" => "2017-05-03 13:20:47"
]
]
In my case if the key "product_id" has the same value I want to reduce merge those arrays and add the total_price but I have to also save a new key to the new array: $quantity to store the number of array with the same key that existed before merging. So the final result should look like this:
array:2 [
0 => array:5 [
"id" => 18
"product_id" => 37
"total_price" => "643.00"
"quantity" => 1
"created_at" => "2017-05-02 13:22:35"
"updated_at" => "2017-05-02 13:22:35"
]
1 => array:5 [
"id" => 19
"product_id" => 36
"total_price" => "1064.00"
"quantity" => 2
"created_at" => "2017-05-02 13:23:47"
"updated_at" => "2017-05-02 13:23:47"
]
]
Initially I tried with array_walk_recursive, but I got confused.
array_walk_recursive($products, function($value, $key) use (&$products_sold){
array_push($products_sold, isset($products_sold[$key]) ? $value + $products_sold[$key] : $value);
});
I know this is useless but I failed to realize how to do this. Any explanation would be helpful. Thank you all for your time!