如何对数组中的多个字段求和

时间:2016-10-18 13:11:00

标签: php laravel laravel-5

我有一个包含价格和数量的收费模型,我希望将价格和数量相乘并对结果求和并更新一个名为bill的表格和最终结果,这里是我的数组

 [
  [
    "Title" => "Price 1",
    "Quantity" => "1",
    "Price" => "1",
  ],
  [
    "Title" => "Price 2",
    "Quantity" => "232",
    "Price" => "32632",
  ],
  [
    "Title" => "Price 3",
    "Quantity" => "11",
    "Price" => "2115",
  ],
]

2 个答案:

答案 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

更多https://laravel.com/docs/5.3/collections#method-sum

答案 1 :(得分:1)

假设$billItems是您的初始数组,您可以在一行中执行此操作:

$grandTotal = array_sum(array_map(function($item) { return $item['Quantity'] * $item['Price']; }, $billItems));