Ahmed Imad Touil
Ahmed Imad Touil

Reputation: 93

How to sum over multiple fields in an array

i have a charges model that contain Price And Quantity , i want to multiply Price and Quantity and sum the results and update a table named bill with final results , here is my array

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

Upvotes: 0

Views: 88

Answers (2)

Jarek
Jarek

Reputation: 194

You can use collections like this

$collection->sum('Price');

or

$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

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

Upvotes: 1

Armin Sam
Armin Sam

Reputation: 933

Assuming that $billItems is your initial array, you can do this in one line:

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

Upvotes: 1

Related Questions