[英]How to use a variable outside of the loop it came from? 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。
讓我知道是否需要其他信息。
先感謝您。
可能是您的查詢結果返回零行數。 確保$ team_query有結果。
result()as $ team_row){$ total + = $ hours; }?>這是解決方案
$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;
算術加法( +
運算符)將不適用於“ 01:00:00”之類的字符串。 您必須將它們轉換為添加之前的秒數(通過TIME_TO_SEC()
MySQL函數),或者按照此處的建議通過SQL計算整個值。
另外,在循環之前查看SQL是很有趣的(通過$ query檢索的SQL):我很確定您可以一次性獲得所有需要的數據,而無需嵌套查詢和PHP計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.