计算总工作时间

问题描述:

我有一个数组,其中包含白天和雇主在白天进出的数据。通常每天只有4行(In -> Out (lunch) -> In -> Out)计算总工作时间

我想根据进/出所有工作小时数,并显示给雇主。

所以,我的天阵列的结构是这样的:

Day '2016-07-01' -> Events (4) -> (0) => ('in', '09:00') 
            (1) => ('out', '13:00') 
            (2) => ('in', '14:00') 
            (3) => ('out', '17:00') 

等等..

向上面下面的代码是印刷6.90这是不正确的例子中,正确的结果应该是8小时。

$total_minutes = 0; 
$total_hours = 0; 

foreach($listOfDays as $day) 
{ 
    foreach($day->events as $key => $event) 
    { 
     // It's always 'in' 
     if(($key % 2 == 0) || $key == 0) 
     { 
     $hour_in = new DateTime($event->hour); 
     $hour_out = null; 

     if(isset($day->events[$key + 1]->hour)) 
      $hour_out = new DateTime($day->events[$key + 1]->hour); 

     if($hour_out != null) 
     { 
      $total_hours += $hour_out->diff($hour_in)->format('%H'); 
      $total_minutes += $hour_out->diff($hour_in)->format('%i'); 
     } 
     } 
     // It's always 'out' 
     else 
     { 
     $hour_in = new DateTime($day->events[$key - 1]->hour); 
     $hour_out = new DateTime($event->hour); 

     $total_hours += $hour_out->diff($hour_in)->format('%H'); 
     $total_minutes += $hour_out->diff($hour_in)->format('%i'); 
     } 
    } 
} 

$total_hours_worked = $total_hours . '.' . $total_minutes; 
print_r($total_hours_worked); 

解决

由于key % 2始终是out移动,因此我不需要in移动的条件,因为out已经过验证。

if($key % 2 != 0) 
{ 
    $hour_in = null; 
    $hour_out = $event->hour; 

    if(isset($day->events[$key - 1]->hour)) 
     $hour_in = $day->events[$key - 1]->hour; 

    if($hour_in != null) 
     $diff += (strtotime($hour_out) - strtotime($hour_in)); 
} 

在该循环的末尾:

$total    = $diff/60; 
$total_hours  = floor($total/60); 
$total_minutes  = floor($total % 60); 
$total_hours_worked = sprintf('%02dh%02d', $total_hours, $total_minutes); 

基于PHP Calculate total time