2016-08-01 166 views
0

我有一個數組,其中包含白天和僱主在白天進出的數據。通常每天只有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); 

回答

0

解決

由於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