2016-08-01 2 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으로 이동하기 때문에 out이 이미 유효하기 때문에 in 이동에 대한 조건이 필요하지 않습니다. PHP Calculate total time

기준

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

다음 루프의 끝에서

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)); 
}