[英]Multiply values in each row in 2d array then calculate grand total
如果我有這個數組:
Array
(
[0] => Array
(
[Price] => 18.00
[Quantity] => 2
)
[1] => Array
(
[Price] => 21.00
[Quantity] => 1
)
)
我怎樣才能將值相加並乘以得到57.00
?
我可以求和但不能乘:
echo array_sum(array_column($datas, 'Price'));
使用array_map()
將每個價格和數量相乘:
$total = array_sum(array_map(function($item) {
return $item['Price'] * $item['Quantity'];
}, $datas));
在這種情況下,您可以使用array_product
進行乘法運算。
$total = array_sum(array_map('array_product', $datas));
這僅在您的數據中只有這些列時才有效。 如果您有其他未在問題中顯示的列,或者如果您稍后向數據添加更多列,則必須像其他答案一樣專門引用價格和數量列。
您編寫一個循環來處理所有數組項並維護一個累加器來記住總數
$tot = 0;
foreach ( $array as $occ ) {
$tot += $occ['Price'] * $occ['Quantity'];
}
echo $tot;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.