[英]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.