如何从循环中获得总和? (PHP)

时间:2013-08-15 03:33:34

标签: php loops if-statement while-loop sum

有人可以帮助我获得以下循环中$total_h的总和或总数吗? 我只需要在循环结束后显示$ total_h的总和,这样我就知道我工作了多少小时。

 <?php

  $get_time = mysql_query("select * from tbl_timekeep where emp_id = 
                                   'OJT0125' order by date desc");

  while ($fect_time = mysql_fetch_array($get_time))
   {
       if ($fect_time[3] == '----' || $fect_time[3] == 'No Out')
          {
          $out = '17:00:00';
          }
       else
          {
          $out = $fect_time[3];
          }

   $from = new DateTime($fect_time[2]);
   $to = new DateTime($out);
   $total_h = $from->diff($to)->format('%h.%i');``
   echo $fect_time[2].'to'.$fect_time[3]." = [ $total_h ]<br>";

  }

  ?>

2 个答案:

答案 0 :(得分:0)

添加代码以总结$ total_h;

$sum_total_h = 0;//initialize

然后你得到$ total_h。你必须添加这段代码。

$sum_total_h +=$total_h;

然后在循环完成后,您可以回显$ total_h

的总和
echo $sum_total_h;

答案 1 :(得分:0)

     <?php

    $get_time = mysql_query("select * from tbl_timekeep where emp_id = 
                               'OJT0125' order by date desc");
        $sum_total_h = 0;
       while ($fect_time = mysql_fetch_array($get_time))
          {
          if ($fect_time[3] == '----' || $fect_time[3] == 'No Out')
          {
           $out = '17:00:00';
           }
      else
         {
         $out = $fect_time[3];
         }

      $from = new DateTime($fect_time[2]);
      $to = new DateTime($out);
      $total_h = $from->diff($to)->format('%h.%i');``

      $sum_total_h +=$total_h;
      echo $fect_time[2].'to'.$fect_time[3]." = [ $total_h ]<br>";
      }
      echo $sum_total_h;

      ?>