我有一个包含价格和数量的收费模型,我希望将价格和数量相乘并对结果求和并更新一个名为bill的表格和最终结果,这里是我的数组
[
[
"Title" => "Price 1",
"Quantity" => "1",
"Price" => "1",
],
[
"Title" => "Price 2",
"Quantity" => "232",
"Price" => "32632",
],
[
"Title" => "Price 3",
"Quantity" => "11",
"Price" => "2115",
],
]
答案 0 :(得分:1)
你可以使用这样的集合
$收藏 - >总和( '价格');
或
$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
答案 1 :(得分:1)
假设$billItems
是您的初始数组,您可以在一行中执行此操作:
$grandTotal = array_sum(array_map(function($item) { return $item['Quantity'] * $item['Price']; }, $billItems));