dongsaoshuo4326 2015-01-19 10:56
浏览 17
已采纳

PHP添加数组的值

I have an array that looks like this, this array represents number of products in a shopping cart

Array
(
    [0] => Array
        (
            [id] => 1
            [icon] => bus.png
            [name] => Web Development
            [cost] => 500
        )

    [1] => Array
        (
            [id] => 4
            [icon] => icon.png
            [name] => Icon design
            [cost] => 300
        )

    [2] => Array
        (
            [id] => 5
            [icon] => icon.png
            [name] => footer design
            [cost] => 300
        )

)

and i am trying to add the [cost] of each together, since it is a shopping cart I need to display the total. some people might buy single product or 2 or 3 so how do i display the total by adding the cost together I have tried using array_sum($products['cost']) and array_sum($products[0]['cost']) but that does not work

  • 写回答

3条回答 默认 最新

  • doutan6286 2015-01-19 11:12
    关注

    For PHP >= 5.5, you can take advantage of PHP's array_column() function

    $total = array_sum(
        array_column(
            $myArray, 
            'cost'
        )
    );
    

    For earlier versions of PHP, you can emulate this using array_map():

    $total = array_sum(
        array_map(
            function($value) { 
                return $value['cost']; 
            }, 
            $myArray
        )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊