0

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",
  ],
]
2
  • And what is your problem exactly? Have you tried doing it "manually" by iterating over this array? I am not sure where your problem begins. Commented Oct 18, 2016 at 13:14
  • i dont know ho to it , to explain the problem i have a dinamic form with multiple fields , and t store the fields in an $charges array wich i need to multiply the price and quantity in order to update bill table Commented Oct 18, 2016 at 13:16

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

5 Comments

how to multiply Price And Quantity before using sum
$addition = $addition ->each(function ($item, $key) { // add new property $item['val'] = price * qty });
$add = $add ->each(function ($item, $key) { // add new property $item['val'] = price * qty }); $collection->sum($add ); like that ?
Should return 7593890 ( (1*1)+(232*32632)+(11*2115) )
Do You try it? ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.