【问题标题】:Laravel: how to group by date and calculate number of hoursLaravel:如何按日期分组并计算小时数
【发布时间】:2019-11-16 01:55:07
【问题描述】:

这更像是一个逻辑问题。我为每个用户的所有考勤日志设计了这个表格

我可以计算每行的时间差和工作小时数。 我需要做的是计算每个日期的小时数,然后每天减去 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
            }
        }
    }
}   

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

谢谢

【问题讨论】:

  • 如何区分用户? emo_number?
  • 是的,这是每个用户的唯一标识符

标签: php laravel


【解决方案1】:

我没有对此进行测试,但它可以让您了解如何解决它

<?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,
];

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多