Reputation: 87
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'));
Upvotes: 0
Views: 172
Reputation: 41810
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
Upvotes: 1
Reputation: 780889
Use array_map()
to multiply each price and quantity:
$total = array_sum(array_map(function($item) {
return $item['Price'] * $item['Quantity'];
}, $datas));
Upvotes: 1
Reputation: 94662
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;
Upvotes: 0