PHP中的多维数组、乘法和加法
我有一个多维数组,如下所示:PHP中的多维数组、乘法和加法,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个多维数组,如下所示: Array( [0] => Array ( [name] => item 1 [quantity] => 2 [price] => 20.00 ) [1] => Array ( [name] => item 2 [quantity] => 1
Array(
[0] => Array
(
[name] => item 1
[quantity] => 2
[price] => 20.00
)
[1] => Array
(
[name] => item 2
[quantity] => 1
[price] => 15.00
)
[2] => Array
(
[name] => item 3
[quantity] => 4
[price] => 2.00
)
)
我需要所有这些项目的“总计”。现在很明显,我可以通过以下方式获得这些:
$grand_total = 0;
foreach ($myarray as $item) {
$grand_total += $item['price'] * $item['quantity'];
}
echo $grand_total;
我的问题是-是否可以使用PHP中的任何数组函数在更少的代码行中完成此操作?否。必须定义一个回调函数才能使用
array\u reduce
。这甚至会变得更长,但会使代码更好地可重用
编辑:很长时间没有编写PHP,但这应该可以做到:
function sum_total_price_of_items($sum, $item) {
return $sum + $item['price'] * $item['quantity']
}
echo array_reduce($myarray, "sum_total_price_of_items", 0)
如果您使用的是PHP>=5.3(lambda函数所需),则
array\u reduce
解决方案将更短:
$input = array(
array(
'name' => 'item 1',
'quantity' => '2',
'price' => 20.00,
),
array(
'name' => 'item 2',
'quantity' => '1',
'price' => 15.00,
),
array(
'name' => 'item 3',
'quantity' => '4',
'price' => 2.00,
),
);
$total = array_reduce($input,
function($subtotal, $row) {
return $subtotal + $row['quantity'] * $row['price'];
});
我喜欢这个:
function GrandTotal($temb, $grand=0) {
return ($current=array_pop($temb)) ? GrandTotal($temb, $grand + $current['price'] * $current['quantity']) : $grand;
}
echo GrandTotal($myarray);
php是否优化尾部递归函数?我的第一个猜测是不会。我仍然喜欢它:)。