I’m struggling with code that would group attendance data.
Usually, in cases where arrival and departure are on the same day, it’s not a problem to group the attendance.
The problem becomes if I have a "night shift": arriving at 10pm and leaving at 06am the next day. In that case, I would like to have a new group of attendances. And than If there are any attendance entries for the next day as well (later than the first check-out for that day), I want to combine them into a new group.
$attendances = [
//Group 1
{
"id": 1,
"attendance_date": "2023-08-24",
"time": "11:00:00",
"status": "arrival"
},
{
"id": 2,
"attendance_date": "2023-08-24",
"time": "14:00:00",
"status": "departure"
},
//Group 2
{
"id": 3,
"attendance_date": "2023-08-24",
"time": "22:00:00",
"status": "arrival"
},
{
"id": 4,
"attendance_date": "2023-08-25",
"time": "06:00:00",
"status": "departure"
},
// Group 3
{
"id": 5,
"attendance_date": "2023-08-25",
"time": "10:00:00",
"status": "arrival"
},
{
"id": 6,
"attendance_date": "2023-08-25",
"time": "18:00:00",
"status": "departure"
}
]
My current code for grouping array is this and it only works in some cases.
$currentDate = null;
$groupedAttendances = [];
$currentGroup = [];
foreach ($attendances as $attendance) {
if ($attendance->attendance_date !== $currentDate) {
// New attendance_date encountered, create a new group
$currentDate = $attendance->attendance_date;
if (!empty($currentGroup)) {
$groupedAttendances[] = $currentGroup;
}
$currentGroup = [$attendance];
} else {
// Adding to the current group
$currentGroup[] = $attendance;
}
}
if (!empty($currentGroup)) {
$groupedAttendances[] = $currentGroup;
}
2
Answers
Maybe I was unclear. But I managed to get the wanted result.
Example data from database:
The code for groupping attendances:
Output results:
It is not explained in the question which two entries form attendance pairs. Only the comments ‘Group 1’ etc. give a hint. So my assumption is that they are to be grouped in pairs as they are appearing in the array (hence the use of array_chunk):
Output: