php从开始时间到结束时间获得总工作时间,每天有多个条目

时间:2016-08-26 22:54:38

标签: php mysql arrays associative-array

我试图在时钟输出系统中构建一个时钟。当试图获得用户在特定日期工作的小时数时,我需要总计工作小时数。我有一个startTime(时间戳)和endTime(时间戳),但是我可以在任何给定的日期为用户提供多个条目,然后将它们分解为时钟,然后在午餐后进行,等等。

 array
  (
        [theUser] => Bob Johnson
        [timeId] => 9
        [user_id] => 1
        [weekNo] => 34
        [clockYear] => 2016
        [entryDate] => 2016-08-21
        [startTime] => 2016-08-21 21:57:01
        [endTime] => 2016-08-21 22:45:15
        [updated_at] => 2016-08-21 22:45:15
        [totTime] => 00:48:14
    ) 

    [9] => Array
    (
        [theUser] => Bob Johnson
        [timeId] => 16
        [user_id] => 1
        [weekNo] => 34
        [clockYear] => 2016
        [entryDate] => 2016-08-24
        [startTime] => 2016-08-24 01:00:00
        [endTime] => 2016-08-24 05:15:00
        [updated_at] => 
        [totTime] => 04:15:00
    )
    (
        [theUser] => Bob Johson
        [timeId] => 15
        [user_id] => 1
        [weekNo] => 34
        [clockYear] => 2016
        [entryDate] => 2016-08-24
        [startTime] => 2016-08-24 01:00:00
        [endTime] => 2016-08-24 05:15:00
        [updated_at] => 
        [totTime] => 04:15:00
    )

    (
        [theUser] => Bob Johnson
        [timeId] => 18
        [user_id] => 1
        [weekNo] => 34
        [clockYear] => 2016
        [entryDate] => 2016-08-24
        [startTime] => 2016-08-24 09:59:00
        [endTime] => 2016-08-24 10:45:00
        [updated_at] => 2016-08-24 10:19:31
        [totTime] => 00:46:00
    )

我需要制作一个新的数组,总计工作时间总结起来我想实现这样的目标

         (
                [theUser] = Bob Johnson
                [weekNo] = 34
                [Year] = 2016
                [entryDate] = 2016-08-24
                [totalHoursWorked] = 09:16:00
                [overTime] = 01:16:00
            )

任何人都可以帮忙解决这个问题

          $startTime = strtotime($val['startTime']);
          $endTime = strtotime($val['endTime']);
          $tot += $endTime - $startTime;

          echo date('H:i:s', $tot)

在foreach循环中,但我总是得到错误的值

2 个答案:

答案 0 :(得分:2)

问题在于您的上一行:echo date('H:i:s', $tot)

您应该使用gmdate代替:

echo gmdate('H:i:s', $tot);

或使用简单的数学代码对其进行格式化:

$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;

echo "$hours:$minutes:$seconds";

答案 1 :(得分:0)

使用Carbon等库可以更方便地进行计算和格式化