2014-10-07 49 views
0

爲什麼這段代碼沒有爲每個用戶累計我的花費時間?php數組不總計數字

while ($row = $result->fetch_assoc()) 
{ 
    $total_spent_time += $row['spent_time']; 

    if (!array_key_exists($row['activity_type'], $data)) 
    { 
     $data[$row['activity_type']] = array(
      'spent_time' => array('user' => array()) 
     ); 

     $data[$row['activity_type']]['spent_time']['user'][$row['user']] = array('time' => $row['spent_time']); 

     if (array_key_exists($row['user'], $data[$row['activity_type']]['spent_time']['user'])) 
     { 
      $data[$row['activity_type']]['spent_time']['user'][$row['user']]['time'] += $row['spent_time']; 
     } 
    } 

它只給出了該行的最後一個值。

+0

這段代碼是在一個循環中,在循環之前設置一個變量爲0,添加到循環中。 – visualex 2014-10-07 10:13:51

+1

這不是一個整數值,我猜。 – prava 2014-10-07 10:14:17

+0

顯示一個示例輸入行,並使用'print_r($ data)' – RiggsFolly 2014-10-07 10:24:16

回答

0

嘗試循環之前申報櫃檯:

$total_spent_time = 0; 
while ($row = $result->fetch_assoc()) { 
    $total_spent_time += $row['spent_time']; 
} 
echo $total_spent_time; 
0

你做錯了一些地方,我們需要查詢和ResultSet的一些細節。
您沒有在數組分配中的任何位置使用$ total_spent_time。

$data[$row['activity_type']]['spent_time']['user'][$row['user']] = array('time' => $row['spent_time']); 

因爲你只使用$行[「spent_time」],並且因爲沒有第二個循環的if語句executs只有一次每用戶($行[「用戶」])
這就是你只能得到理由1值。

+0

是的,你完全正確。謝謝! – Nikage 2014-10-08 09:25:41

+0

@Nikage不客氣 – 2014-10-08 09:26:22