开发者

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 开发者_JAVA技巧in PHP?


no. you would have to define a callback function to use 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:

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:

$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜