我的问题是一个数组,该数组存储插入购物车中的所有项目。购物车商品具有以下结构:
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
]
]
我已经尝试过以下解决方案: Sum of subarray values, php array group, http://sandbox.onlinephpfunctions.com/code/3db42a4e13464eb027d85549f897a313fb8250eb
此结果是由以下代码产生的:
($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;
}
}
我想做的是: -更改每个商品的价格 数量> 1。 -同时,将来自 相同的卖方。
(因此数组中存储了多个相同的项目)。我认为可以执行以下操作:
if($ar['quantity'] > 1){
$newarray[$v]['price'] = $newarray[$v]['price'] * $ar['quantity'] + $ar['price'] * $ar['quantity'];
}
数量大于1的商品的所需结果为:
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
]
]
我认为有效的解决方案是@mickmackusa在PHPSandbox中找到的一个示例提出的解决方案 http://sandbox.onlinephpfunctions.com/code/3db42a4e13464eb027d85549f897a313fb8250eb