To achieve the desired collection structure where each employee is assigned to specific shifts based on a pattern, you can use a combination of looping and conditional logic to distribute the shifts among the employees. Here's a possible solution using Laravel's collection methods:
$shifts = collect(range(0, 52));
$employeeIds = collect(range(1, 16));
// Initialize an empty collection to store the final sets
$sets = collect();
// Loop through each employee ID
foreach ($employeeIds as $employeeId) {
// Calculate the shifts for each employee based on their ID
$employeeShifts = $shifts->filter(function ($shift) use ($employeeId, $employeeIds) {
return ($shift % $employeeIds->count()) == ($employeeId - 1);
});
// Add the result to the sets collection
$sets->push([
'employee' => $employeeId,
'set' => $employeeShifts->values()->all()
]);
}
// Output the result
print_r($sets->all());
Explanation:
- Initialize Collections: We start by creating collections for shifts and employee IDs.
- Create an Empty Collection for Sets: This will store the final structured data.
- Loop Through Each Employee: For each employee, we determine which shifts they should be assigned.
-
Filter Shifts: The
filtermethod is used to select shifts for each employee. The condition inside the filter ensures that the shift is distributed evenly based on the employee's ID. The modulo operation (%) helps in evenly distributing shifts among employees. -
Add to Sets Collection: Each employee's ID and their corresponding shifts are added to the
setscollection. -
Output the Result: Finally, we print out the
setscollection.
This solution ensures that each employee is assigned shifts in a round-robin fashion, and it dynamically adjusts based on the total number of shifts and employees.