【问题标题】:Summing an associative array based on key value基于键值对关联数组求和
【发布时间】:2017-11-15 08:37:08
【问题描述】:

我有一个从 mysql 获取的关联数组,我需要根据不同列中的值对值求和。我创建了一个关联数组,并打印到屏幕上,看起来还不错。它返回我需要的东西,看起来像[1] => 779700.00 ) Array ( [4] => 868.00 ) Array ( [2] => 102000.00 ) Array ( [2] => 775808.00

我的问题是我需要能够对每个单独的键值对的结果求和(例如,'2' 的总和为 877808.00)——只有八个键值,我需要一个变量来保存每个键值.我已经阅读了很多类似的问题并尝试了解决方案,但只是让自己陷入了无可救药的困惑。

我假设我需要一个 foreach 循环,请有人指出我需要做什么的正确方向吗?

while($row_outputs=mysqli_fetch_array($run_projects))
                { 

                $Id = $row_outputs['id']; 
                $impact = $row_outputs['impact']; 
                $cost = $row_outputs['total_cost']; 

                $summing_array = array($impact=>$cost); 

【问题讨论】:

    标签: php arrays associative-array


    【解决方案1】:

    我会创建一个新数组来保存总和的结果,然后为每一行检查结果数组中是否已经有该 $impact 的条目。如果不创建它,如果是,则将 $cost 添加到它。可以这样做:

        $results = [];
        while ($row_outputs = mysqli_fetch_array($run_projects)) {
    
            $Id = $row_outputs['id'];
            $impact = $row_outputs['impact'];
            $cost = $row_outputs['total_cost'];
    
            if(isset($results[$impact])){
                $results[$impact] += $cost;
            }else{
                $results[$impact] = $cost;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2014-07-19
      • 2012-12-21
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多