Problem I'm having occured while building php script to automaticaly generate graph based on values from database.
I'm having all 12 months listed on X line and sum of monthly income for each month on Y line. In order to keep same size of graph everytime i want to convert sum of monthly income to % inpact on all graph, to do that i will use simple formula:
(array element / sum of all array elements) * 100
this should tell which % part of all graph is each array element
code is rather straight forward:
foreach($years as $year) {
// Do something
foreach($months as $month) {
foreach( // this foreach is getting monthly income foreach month \\ ) {
// so in here we get $total_by_date[$year][$month];
}
$year_total[$year] += $total_by_date[$year][$month]; //sum of (sum of each month income)
?>
<div style="background:black;height:20px;width:<?php echo ($total_by_date[$year][$month] / $year_total[$year]) * 100 ?>px;">div> //drawing graph based on given values
<?php
}
}
I checked it in various conditions and it appears to be working corectly, i got list of months foreach year, within months i got monthly income foreach month properly displayed. Still, essentialy its not working, in order it to fuly work i would need to get total income foreach year before i start outputing that draws graph, instead while each element from foreach loop is being scanned and displayed suming function is doing array walk so its incresing total value with each scanned month, at the end is giving few errors beacuse of january and february 0 income, even though year income should be 6700 - in few first months is displaying 2400, then 3500 then 5400 and finally 6700 at december.
i guess that i would need to get total year income before foreach starts with outputs month by month, the problem is i dont know how to do that. I came up with:
if(empty($year_sub[$year])) { unset($year_sub[$year]); continue; }
placed before div output, it helped a little, it removed all the initial 0's so it doesnt crash at the begining anymore, but still is doing sum on the fly which screws up the idea.
perhaps someone know how to start and finish suming before output or some other great solution. Thank You in advance.