Laravel:如何按日期分组并计算小时数

时间:2019-11-16 01:55:07

标签: php laravel

这更多是一个逻辑问题。我有针对每个用户的所有出勤记录的表格设计

attendance_logs table

我可以计算出每一行的时差和工作时间。 我需要做的是计算每个日期的小时数,然后每天减去8小时以获得加班时间。

for($i=0; $i < count($logs)-1; $i++ ){
    if($logs[$i]->status == 'out'){
        if ($i != 0) {
            $dattime1 = new Carbon($logs[$i]->log_date.' '. $logs[$i]->log_time);
            if ($logs[$i-1]->status == 'in') {
               $dattime2 = new Carbon($logs[$i-1]->log_date.' '. $logs[$i-1]->log_time);
               $diff = $dattime1->diff($dattime2);
               $hr_array[] = $diff->h;
               $min_array[] = $diff->i;
               $sec_array[] = $diff->s;
               $arr[] = $diff
            }
        }
    }
}   

每行我可以得到几分钟和几小时。我想将具有相同日期的行分组,并计算总工作时间,这样我就可以加班。

谢谢

1 个答案:

答案 0 :(得分:0)

我没有对此进行测试,但是它可以为您提供解决方法的思路

<?php

// for each date, keep adding difference in minutes here
// use date as array key
$workedMinutesPerDay = [
  // '2019-11-04' => minutes value
];

// keep 'in' date value here
$inDate = '';

foreach($logs as $log) {
  $date = new Carbon($log->log_date.' '. $log->log_time);

  // if 'in' value, remember the date and time and continue to next row
  // next row should be out
  if ($log->status = 'in') {
    $inDate = $date;
    continue;
  }

  // if you will always have 'in' then 'out' in order, this code is fine
  // but you should handle inconsistencies here

  // use remembered 'in' value stored in $inDate to calculate the diff in minutes
  $diffInMinutes = $date->diffInMinutes($inDate);

  // use $workedMinutesPerDay array with 'log_date' as key
  // if we don't have the entry for the day, add new one
  if (empty($workedMinutesPerDay[$log->log_date])) {
    $workedMinutesPerDay[$log->log_date] = $diffInMinutes;
  }

  // date entry was already there, add current diffInMinutes to previous value
  $workedMinutesPerDay[$log->log_date] += $diffInMinutes;
}

运行此命令后,您将具有这样的数组(假设值),没有从图片中计算出真实值

$workedMinutesPerDay = [
  '2019-11-04' => 100, // total minutes for the day
  '2019-11-05' => 200,
  '2019-11-08' => 300,
  '2019-11-11' => 400,
  '2019-11-12' => 500,
];