0

If I have this array:

Array
(
    [0] => Array
      (
            [Price] => 18.00
            [Quantity] => 2
      )
    [1] => Array
      (
            [Price] => 21.00
            [Quantity] => 1
      )
)

How can I sum and multiply the value to get 57.00 ?

I can sum but not multiply:

echo array_sum(array_column($datas, 'Price'));
2
  • 1
    You write a loop to process all the array items and maintain an accumulator to remember the total Commented Aug 31, 2021 at 17:01
  • Or array_reduce: array_reduce($whatever, function ($a, $e) { return $a + $e['Price'] * $e['Quantity']; }, 0)... Does this answer your question? multidimensional array array_sum. Just add * $e["Quantity"] to just about any answer here; the array_column/array_sum combo doesn't work because it doesn't know how to apply multiplication, but anything that has a function body or loop body will give you a chance to apply the desired operation. Commented Aug 31, 2021 at 17:05

3 Answers 3

1

Use array_map() to multiply each price and quantity:

$total = array_sum(array_map(function($item) { 
    return $item['Price'] * $item['Quantity']; 
}, $datas));
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. It give me this error: array_map() expects at least 2 parameters, 1 given.
Pass your array as the second argument to array_map. I've updated the post since I'm sure that was Barmar's intent and it was just a typo.
So what is $item ?
That's each inner array of the outer array. You can var_dump($item) on each iteration of the callback to inspect it.
1

You can use array_product for the multiplication in this case.

$total = array_sum(array_map('array_product', $datas));

This will only work if those are the only columns in your data. If you have other columns that you aren't showing in the question, or if you add more columns to your data later, you'll have to specifically refer to the price and quantity columns like the other answers do.

For example: https://3v4l.org/qCHbZ

2 Comments

Yup, this is the most elegant solution for this task.
Also found identically posted by you in 2018
0

You write a loop to process all the array items and maintain an accumulator to remember the total

$tot = 0;
foreach ( $array as $occ ) {
    $tot += $occ['Price'] * $occ['Quantity'];
}
echo $tot;

Comments

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.