dqwh1218 2018-02-21 12:54
浏览 140
已采纳

累计总foreach循环,使用变量到组号[重复]

This question already has an answer here:

I need help regarding foreach and arrays in PHP

Say I have the following array:

$orders = array (
  0 => 
    array (
      'company' => 'Company 1',
      'total' => '5',
    ),
  1 => 
    array (
      'company' => 'Company 2',
      'total' => '10',
    ),
  2 => 
    array (
      'company' => 'Company 1',
      'total' => '15',
    ),
  3 => 
    array (
      'company' => 'Company 1',
      'total' => '5',
    ),
  4 => 
    array (
      'company' => 'Company 3',
      'total' => '12',
    )
);

Order 1 is 5 for Company 1
Order 2 is 10 for Company 2
Order 3 is 15 for Company 1
Order 4 is 5 for Company 2
Order 5 is 12 for Company 3

I want the output to show the company name and the accumulative total of each company's orders

For example:

Company 1           20
Company 2           15
Company 3           12
</div>
  • 写回答

4条回答 默认 最新

  • dqtok88424 2018-02-21 13:03
    关注

    Just create another array that will track the orders.

    $companies = array();
    foreach ($orders as $order) {
        if (array_key_exists($order["company"], $companies)) {
            $companies[$order["company"]] += $order["total"];
        } else {
            $companies[$order["company"]] = $order["total"];
        }
    }
    

    First, we check if the company is already in the companies array, if it is then we add the total to that company's current total.
    Otherwise, we just create a new key and store the total.

    Additionally, you can write (int)$order["total"] to typecast into integer.
    This might be useful to ensure that you have the correct data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集