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