在 foreach 循环内处理具有相同 ID 的多个记录 PHP

Handling multiple records with same ID, inside a foreach loop PHP

这是一个考勤管理系统,让我解释一下它的结构。 这里有两个table,一个是tbl_temperory &另一个是tbl_review,

tbl_temperory

Autoid | emp_id | att_date | att_time
-------------------------------------
100    | 05     |05/25/2022| 07.30
101    | 05     |05/25/2022| 09.30
102    | 05     |05/25/2022| 18.30
103    | 06     |05/25/2022| 08.30
104    | 06     |05/25/2022| 20.30

tbl_review

Autoid | emp_id | att_date | clock_in | clock_out
-------------------------------------------------
200    | 05     |05/25/2022| 18.30    |
201    | 06     |05/25/2022| 08.30    | 20.30

当用户签到或签出初始记录更新到临时table时,有时用户可以多次签到和签出,因此临时table可能有多个记录同一个用户。

在一天结束时,有一个获取出勤记录的选项,它会更新为 tbl_review

现在的问题是,当一个员工只有两条记录时,tbl_review 完美地更新了 clock_in & clock_out。但是当有多个记录时,它只更新最后一个记录时间为clock_in时间。

我在下面附上了 foreach 循环如何更新评论 table,有人可以指导我,我在哪里犯了错误。

谢谢。

$temp = All records from temp table Stored here
 if ($temp) { 
   $i = 0;
   $employee = '';
   $continue = FALSE;
   foreach ($temp as $row) {
    if ($continue) {   
      $continue = FALSE;
      $i++;
      continue;
    }
    $employee = $row['emp_id'];
    $attendanceDate = $row['att_date'];
    $clockIn = $row['att_time'];
    $nextKey = $i + 1;
    $clockOut = NULL;
     if (array_key_exists($nextKey, $temp)) {
        if ($temp[$nextKey]['emp_id'] == $row['emp_id'] && $attendanceDate == $temp[$nextKey]['att_date']) {
                    $clockOut = $temp[$nextKey]['att_time'];
                    $continue = TRUE;
                }

    }
  }
 }

实际上,您可以使用单个插入查询来完成此操作。 user/employee 的 clock_in 时间将是所有打卡时间中最少的,而 clock_out 将是给定日期所有打卡时间中的最大值。

因此,您可以使用 PDO 构造一个查询,并通过准备好的语句将手头的当前日期注入到以下查询中:

insert into tbl_review(emp_id, att_date,clock_in, clock_out) 
SELECT emp_id, att_date , min(STR_TO_DATE(att_time, '%H.%i:%s')) as clock_in, max(STR_TO_DATE(att_time, '%H.%i:%s')) as clock_out
FROM `tbl_temperory`
where att_date = '05/25/2022' -- your date variable here
group by emp_id

与您的代码具有相似的逻辑,假设您的记录与您显示的记录相似(升序 emp_id 和 att_time)。

if ($temp) {
    $i = 0;
    $newID = TRUE;
    foreach ($temp as $row) {
        $employee = $row['emp_id'];
        $attendanceDate = $row['att_date'];
        $nextKey = $i + 1;
        
        if ($newID) {
            $clockIn = $row['att_time'];
            addClockInToTblReview($employee, $attendanceDate, $clockIn);
        }
        
        if (array_key_exists($nextKey, $temp)) {
            if ($temp[$nextKey]['emp_id'] != $row['emp_id'] || $attendanceDate != $temp[$nextKey]['att_date']) {
                $clockOut = $row['att_time'];
                addClockOutToTblReview($employee, $attendanceDate, $clockOut);
                $newID = TRUE;
            } else {
                $newID = FALSE;
            }
        }
        $i++;
    }
}

逻辑是迭代每个数据条目,

  • 如果它是具有相同 ID 和日期的第一个条目,则更新 clockIn
  • 如果下一个数据条目具有不同的 ID 或不同的日期,则更新 clockOut
  • 否则什么也不做并继续

ps。写你自己的 addClockInToTblReviewaddClockOutToTblReview 因为没有提供太多关于数据库的信息