<?php
$staff = array(1,2,3,4,5);
$start = array("11:05", "11:00", "19:00", "13:00", "19:00");
$end = array("16:00", "17:00", "03:00", "16:00", "03:05");
// Add staff number to end of time ex 11:00 => 11:00#2
For($i=0; $i<count($start);$i++){
$start[$i] .= "#" . $staff[$i];
$end[$i] .= "#" . $staff[$i];
}
$t = array_merge($start,$end); // create one long array with all in and out times
sort($t);
// Multisport is needed to get all arrays in time order as reference
array_multisort($start, $end, $staff);
// Find first start time (11:00) and slice array thwre, build string
$test = implode(PHP_EOL,array_slice($t, array_search($start[0], $t)));
// Find the times before first start (night end times) and add them last in string
$test .= PHP_EOL . implode(PHP_EOL,array_slice($t, 0,array_search($start[0], $t)));
$times = explode(PHP_EOL, $test); // explode to make it array again
// Var_dump($times);
$WhoIsInDaHouse = array("dummy"); // add a dummy variable since 0=false in later if
$j=0;
for($i=0; $i<count($times);$i++){
$TimePerson = explode("#", $times[$i]);
$Time = $TimePerson[0];
$person = $TimePerson[1];
$inout = array_search($person, $WhoIsInDaHouse); //is person in house and about to leave?
If($inout != false){ //if person enter work false, if true: key of person leaving in $WhoIsInDaHouse
//Here $person is leaving work
Unset($WhoIsInDaHouse[$inout]);
If(count($WhoIsInDaHouse) == 2){ // someone will now be alone since we have a dummy
$Alone[$j]["start"] = $Time;
$Alone[$j]["who"] = array_slice($WhoIsInDaHouse, -1)[0];
}elseif(count($WhoIsInDaHouse) == 1 && $prevcount == 2){
// Only dummy left
$Alone[$j]["end"] = $Time;
$Alone[$j]["duration"] = strtotime($Alone[$j]["end"])-strtotime($Alone[$j]["start"]);
$j++;
}
}Else{
// Here person enters work
$WhoIsInDaHouse[] = $person;
If(count($WhoIsInDaHouse) == 2){ // someone is entering alone
$Alone[$j]["start"] = $Time;
$Alone[$j]["who"] = $person;
}elseif(count($WhoIsInDaHouse)>2 && $prevcount == 2){ // not alone anymore
$Alone[$j]["end"] = $Time;
$Alone[$j]["duration"] = strtotime($Alone[$j]["end"])-strtotime($Alone[$j]["start"]);
$j++;
}
}
$prevcount = count($WhoIsInDaHouse);
}
Var_dump($Alone);