bevc Posted June 14, 2017 Share Posted June 14, 2017 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 More sharing options...
Larry Posted June 14, 2017 Share Posted June 14, 2017 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! 1 Link to comment Share on other sites More sharing options...
bevc Posted June 15, 2017 Author Share Posted June 15, 2017 Interesting! I'd create an array outside of your loop, call it $totals. Hope that helps! That worked, thank you so much, you saved my life! Link to comment Share on other sites More sharing options...
Larry Posted June 15, 2017 Share Posted June 15, 2017 Absolutely welcome and thanks for letting me know! 1 Link to comment Share on other sites More sharing options...
Recommended Posts