2016-09-14 28 views
0

的總和我知道得到兩個數組的總和,但是這一次是不同的,我不能再取,我有一個循環和值是從數據庫中來。從我的代碼循環的實際迭代是兩次,因爲它是嵌套的,我的意思是它循環兩次或但它取決於我的數據,但現在它只有兩次,值是彼此不同。PHP:獲得兩個數組有相同的變量名

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 

但是,如果我在循環外顯示$數組的值,僅顯示第一

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

我怎樣才能獲得第一和第二陣列的總和,並得到像

結果
196.67 
190.00 
119.33 
74.67 
50.00 
50.00 
+0

檢查http://stackoverflow.com/questions/15549045/best-method-for-sum-two-arrays – jitendrapurohit

+0

其中一個具有不同的數組變量名稱 –

+0

你可以發佈你的'$ array'構建的代碼嗎? – jitendrapurohit

回答

0

這應該工作:

$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. 
相關問題