douji8033 2011-01-07 10:12
浏览 27
已采纳

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?

  • 写回答

3条回答 默认 最新

  • duan1979768678 2011-01-07 10:14
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用