0

I know to get sum of two arrays but this one is different I can't take anymore, I have a loop and the values are came from database. The actual iteration of loop from my code is twice because it is nested, what i mean is it looping twice or but it depends on my data but as for now it only twice and the values are different to each other.

 while(){....       

 //nested loop

 $array = array();
 while($row = mysql_fetch_assoc($query)){ //<--Looping twice but different values
     array_push($array , number_format((float)$row ['total'],2,'.',''));
 }

 foreach($array as key => value){
     echo $value . "<br/>";
 }


 {.....

 //the values of loop that i fetch
 //first <-- $array
  97.00 <-- 0 key
  92.67 <-- 1 key
  72.33 <-- 2 key
  49.67 <-- 3 key
  25.00 <-- 4 key
  25.00 <-- 5 key

 //Second <-- $array     
  99.67 <-- 0 key
  97.33 <-- 1 key
  47.67 <-- 2 key
  25.00 <-- 3 key
  25.00 <-- 4 key
  25.00 <-- 5 key

 //The first and second are same variable name $array but its values are different

However, if i display the value of $array outside the loop it shows only the first

 97.00 <-- 0 key
 92.67 <-- 1 key
 72.33 <-- 2 key
 49.67 <-- 3 key
 25.00 <-- 4 key
 25.00 <-- 5 key

How can I get the sum of first and second array and get the result like

 196.67
 190.00
 119.33
 74.67
 50.00
 50.00
Raffy T Lawrence
  • 315
  • 1
  • 6
  • 18

1 Answers1

0

This should work:

$i = 0;
$sumArray = array();
while($row = mysql_fetch_assoc($query)) { 
  //calculate the total and push it in the array.
  $total = $array[$i] + number_format((float)$row ['total'],2,'.','');
  array_push($sumArray, $total); 
  array_push($array , number_format((float)$row ['total'],2,'.',''));
  $i++;
}

print_r($sumArray); //this should give you the total array.
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39