如何使用它来自循环之外的变量? PHP

时间:2016-02-18 03:59:07

标签: php sql codeigniter foreach

自发布以来,我已更新了我的代码。

我试图在计算的循环之外回显一个变量。

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。

如果需要任何其他信息,请与我们联系。

提前谢谢。

3 个答案:

答案 0 :(得分:0)

可能是您的查询结果返回ZERO行数。确保$ team_query有结果。

   result()as $ team_row)  { $ total + = $ hours;   }?&gt;

答案 1 :(得分: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;

答案 2 :(得分:0)

算术加法(+运算符)不会像&#34; 01:00:00&#34;那样在字符串上工作。您必须在添加之前将它们转换为秒(通过TIME_TO_SEC() MySQL函数),或者通过SQL计算整个值,如建议here

另外,在循环之前查看SQL(通过$ query检索的那个)会很有趣:我非常确定你可以一次性获得所需的所有数据,而不需要嵌套查询和PHP计算。