2016-02-18 50 views
0

自我發佈以來,我已經更新了我的代碼。如何在循環外部使用變量? PHP

我試圖呼應它在計算環路以外的變量。

foreach ($query->result() as $row){ //loop to display all team members 


    echo '<table border="1"><tr><td>User</td><td>Hours</td></tr>'; 

    $this->db->select('users.USER_EMAIL'); //we want to display the users' emails who are in this team. 
    $this->db->from('users'); 
    $this->db->join('user_teams', 'users.USER_ID = user_teams.USER_ID'); //we need to join these tabels in order to get this 
    $this->db->join('teams', 'teams.TEAM_ID = user_teams.TEAM_ID'); 
    $this->db->where('teams.TEAM_NAME', $row->TEAM_NAME); //search for the team name that we are currently looking at 
    $team_query = $this->db->get(); 


    echo '<h2>Team: '; 
    echo $row->TEAM_NAME; 
    echo '</h2>'; 
$total = date('h:i:s', NULL); 
var_dump($total); //outputs "01:00:00" as a string 
foreach ($team_query->result() as $team_row) { 

var_dump($total); //outputs "01:00:00" as a string 


echo '<tr>'; 
echo '<td>'; 
echo $team_row->USER_EMAIL; 
echo '</td>'; 

$this->db->select('SEC_TO_TIME(SUM(TIME_TO_SEC(`USER_WORK_HOURS`))) AS totalHours'); 
$this->db->where('USER_EMAIL', $team_row->USER_EMAIL); 
$hours= $this->db->get('user_hours')->row()->totalHours; 

echo '<td>'; 
echo $hours; //outputs "00:11:01" as a string, that is the correct value 
echo '</td>'; 
var_dump($hours); //outputs "00:11:01" as a string. still correct 
$total += $hours; //im guessing the += operators do not work on time 
var_dump($total); //outputs 1 as int, not correct. should be "00:11:01" as a string for the first time around the loop 

echo '</tr>'; 
echo '<br />'; 
} 
    echo '<tr>'; 
    echo '<td>'; 
    echo 'Total'; //outputs 1 as int 
    echo '</td>'; 
    echo '<td>'; 
    echo $total; //outputs 1 as int 
    echo '</td>'; 
    echo '</tr>'; 
    echo '</table>'; 

}  

莫非有什麼用它做的時間格式是?

添加時間的正確方法是什麼?

我使用codeigniter 3x如果重要的話。

讓我知道是否需要任何額外的信息。

預先感謝您。

+0

顯然,你的'$ team_query-> result()'不會返回任何結果,而且你的腳本甚至不會輸入'foreach'。先嚐試調試這一個。 (是的,你應該總是事先初始化你的變量。) –

+0

變量$ hours確實輸出。所以查詢返回結果 – Ddrossi93

+0

在一個不相關的說明中,在循環中運行SQL查詢是一個壞主意。考慮讓這個計算成爲你的$ team_query的一部分。 –

回答

0

可能是您的查詢結果返回ZERO行數。確保$ team_query有結果。

result()as $ team_row) { $ total + = $ hours; }?>
+0

它確實返回行。變量$小時輸出正確 – Ddrossi93

+0

首先,您必須爲$ total創建初始值。所以在循環的外面你應該聲明$ total = 0;那就是循環的開始。 – Gopalakrishnan

+0

我已經添加了更多的代碼。我很積極,查詢返回結果。它可能與它是一個時間格式有關嗎? – Ddrossi93

0

下面是解

 $hours= $this->db->get('user_hours')->row()->totalHours; 

     make sure that $hours variable contains an integer value 
     or float value 
     it should not a be string and also not be empty. 


You can initialize $total = 0; $hours=0; 
+0

我從數據庫中抓取的值是時間格式。這可能是爲什麼他們沒有正確添加。有沒有辦法添加他們沒有任何問題? – Ddrossi93

0

算術加法(+運營商)也不會像 「01:00:00」 字符串的工作。您必須將它們轉換爲添加之前的秒數(通過TIME_TO_SEC() MySQL函數),或者通過SQL計算整個值,如建議here

另外,在循環之前查看SQL(通過$ query檢索的)會很有趣:我非常確定您可以一次性獲取所需的所有數據,而無需嵌套查詢和PHP計算。