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'));
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Maman
  • 97
  • 6
  • 1
    You write a loop to process all the array items and maintain an accumulator to remember the total – RiggsFolly Aug 31 '21 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](https://stackoverflow.com/questions/12838729/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. – ggorlen Aug 31 '21 at 17:05

3 Answers3

1

Use array_map() to multiply each price and quantity:

$total = array_sum(array_map(function($item) { 
    return $item['Price'] * $item['Quantity']; 
}, $datas));
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks for your help. It give me this error: `array_map() expects at least 2 parameters, 1 given`. – Maman Aug 31 '21 at 17:10
  • 1
    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. – ggorlen Aug 31 '21 at 17:11
  • So what is `$item` ? – Maman Aug 31 '21 at 17:12
  • 1
    That's each inner array of the outer array. You can `var_dump($item)` on each iteration of the callback to inspect it. – ggorlen Aug 31 '21 at 17:13
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

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
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;
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149