我有一个包含价格和数量的收费模型,我想将价格和数量相乘,并将结果求和,并使用最终结果更新名为bill的表,这是我的数组
[
[
"Title" => "Price 1",
"Quantity" => "1",
"Price" => "1",
],
[
"Title" => "Price 2",
"Quantity" => "232",
"Price" => "32632",
],
[
"Title" => "Price 3",
"Quantity" => "11",
"Price" => "2115",
],
]
假设$billItems
是您的初始数组,您可以在一行中完成:
$grandTotal = array_sum(array_map(function($item) { return $item['Quantity'] * $item['Price']; }, $billItems));
你可以这样使用集合
收集->总和("价格");
或
$yourArray = [
[
"Title" => "Price 1",
"Quantity" => "1",
"Price" => "1",
],
[
"Title" => "Price 2",
"Quantity" => "232",
"Price" => "32632",
],
[
"Title" => "Price 3",
"Quantity" => "11",
"Price" => "2115",
]
];
$collection = collect($yourArray);
$payment = $collection->sum(function ($item) {
$item['Price'] = $item['Price'] * $item['Quantity'];
return $item['Price'];
});
dd($payment); // 7593890
更多https://laravel.com/docs/5.3/collections method-sum