<?php
$staff = array(1,2,3,4,5,6,7,8,9,10);
$start = array("11:00", "13:00", "17:00", "17:00", "11:00", "13:30", "16:50", "18:30","17:00", "11:00");
$end = array("21:00", "15:00", "19:00", "19:30", "11:30", "15:10", "18:45", "19:45", "19:00", "11:30");
// 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);
//var_dump($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++){
//echo $times[$i] ." " . $i ."\n";
if($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);
}
}
foreach($Alone as $key => &$loner){
if($loner["duration"]==0) unset($Alone[$key]);
}
Var_dump($Alone);