My problem is with a an array, that stores all the items inserted in a cart. The cart items have the following structure:
array:3 [▼
1 => array:7 [▼
"id" => 1
"name" => "Listing Sample 1"
"quantity" => "1"
"price" => 145.5
"photo" => null
"seller" => 1
"buyer" => 3
]
4 => array:7 [▼
"id" => 3
"name" => "Sample Listing 3"
"quantity" => 1
"price" => 50.5
"photo" => null
"seller" => 4
"buyer" => 3
]
2 => array:7 [▼
"id" => 4
"name" => "Sample Listing 4"
"quantity" => 1
"price" => "30.50"
"photo" => null
"seller" => 2
"buyer" => 3
]
]
I have already tried solutions such as the following: Sum of subarray values , php array group , http://sandbox.onlinephpfunctions.com/code/3db42a4e13464eb027d85549f897a313fb8250eb
This result is produced from the following code:
($arr = session()->get('cart'));
$newarray = array();
foreach($arr as $ar) {
foreach ($ar as $k => $v) {
if (array_key_exists($v, $newarray))
$newarray[$v]['price'] = $newarray[$v]['price'] + $ar['price'] ;
else if ($k == 'seller')
$newarray[$v] = $ar;
}
}
What I would like to do is: - Alter the price for each item that has quantity>1. - At the same time, group all the items that come from the same seller.
(so more than one identical items are stored in the array). I thought that it would be possible to just do the following:
if($ar['quantity'] > 1){
$newarray[$v]['price'] = $newarray[$v]['price'] * $ar['quantity'] + $ar['price'] * $ar['quantity'];
}
And the required result for items that have quantity > 1 would be:
array:3 [▼
1 => array:7 [▼
"id" => 1
"name" => "Listing Sample 1"
"quantity" => "1"
"price" => 145.5
"photo" => null
"seller" => 1
"buyer" => 3
]
4 => array:7 [▼
"id" => 3
"name" => "Sample Listing 3"
"quantity" => 3
"price" => 151.5
"photo" => null
"seller" => 4
"buyer" => 3
]
2 => array:7 [▼
"id" => 4
"name" => "Sample Listing 4"
"quantity" => 2
"price" => "61"
"photo" => null
"seller" => 2
"buyer" => 3
]
]
I think a valid solution is the one proposed from an example found in PHPSandbox by @mickmackusa http://sandbox.onlinephpfunctions.com/code/3db42a4e13464eb027d85549f897a313fb8250eb