基于键值对关联数组求和



我有一个从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); 

我会创建一个新数组来保存您的总和的结果,然后为每一行检查结果数组中是否已经有该$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;
}
}

最新更新