如何从循环中求和?(php)


How to get the sum from the loop? (php)

有人能帮我得到下面循环中$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>";
  }
  ?>
     <?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;
      ?>

添加一个代码来汇总$total_h;

$sum_total_h = 0;//initialize

然后在你得到$totalh之后。您必须添加此代码。

$sum_total_h +=$total_h;

然后循环完成后,您可以返回$total_h 的总和

echo $sum_total_h;