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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作