Jump to content
Larry Ullman's Book Forums

Recommended Posts

This is related to another question I asked that I haven't managed to resolve, so I'm trying something else! I have an associative array fetched from mysql, and I need to sum values based on the value in a different column. I have created an associative array, and printed to screen and it looks okay. It returns what I need, and looks like 

[1] => 779700.00 ) Array ( [4] => 868.00 ) Array ( [2] => 102000.00 ) Array ( [2] => 775808.00

My problem is that I need to be able to sum the results for each individual key value pair (so eg '2' would sum to 877808.00) - there are only eight key values, and I need a variable to hold each one. I have read lots of similar questions and have tried the solutions, but have just got myself hopelessly confused.

I assume I need a foreach loop, please could somebody point me in the right direction for what I need to do? I'm not sure if I'm barking up the wrong tree or not. Thanks.  

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); 
Link to comment
Share on other sites

Interesting! I'd create an array outside of your loop, call it $totals. 

 

Then, within the mysqli_fetch_array() loop, do something like this:

if (array_key_exists($impact, $totals)) {
  $totals[$impact] += $cost;
} else {
  $totals[$impact] = $cost;
}

Hope that helps!

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...