简体   繁体   English

PHP中的多维数组,乘法和加法

[英]Multi-Dimensional Array, Multiplication and Addition in PHP

I have a multidimensional array as follows: 我有一个多维数组如下:

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
        )

)

I need the 'grand total' of all these items. 我需要所有这些项目的“总计”。 Now clearly I could get these by doing the following: 现在很明显我可以通过以下方式获得这些:

$grand_total = 0;
foreach ($myarray as $item) {
    $grand_total += $item['price'] * $item['quantity'];
}
echo $grand_total;

My question is - can this be done in less lines of code using any of the array functions in PHP? 我的问题是 - 可以使用PHP中的任何数组函数在较少的代码行中完成吗?

no. 没有。 you would have to define a callback function to use array_reduce . 你必须定义一个回调函数来使用array_reduce this would even get longer but make the code better reusable. 这甚至会变得更长,但使代码更好地重用。

EDIT: Didn't write PHP for a long time but this should do it: 编辑:没有写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)

If you are using PHP >= 5.3 (needed for lambda functions), then the array_reduce solution would be shorter: 如果您使用PHP> = 5.3(lambda函数需要),那么array_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']; 
                      });

I love this one: 我喜欢这个:

function GrandTotal($temb, $grand=0) {
    return ($current=array_pop($temb)) ? GrandTotal($temb, $grand + $current['price'] * $current['quantity']) : $grand;
}

echo GrandTotal($myarray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM