[英]How can I check for time span conflicts on each day?
上課時間:
Day 1 => 08:00-09:00 | 11:00-12:00 | 13:00-15:00 | 20:00-21:00
Day 2 => 12:00-13:00 | 14:00-15:00
Day 3 => 08:00-09:00 | 16:00-17:00 | 18:00-19:00
Day 4 => 10:00-11:00 | 12:00-14:00 | 14:00-16:00
Day 5 => 08:00-10:00 | 13:00-15:00
Day 6 => 80:00-09:00 | 10:00-11:00
B級時間:
Day 1 => 10:00-11:00 | 17:00-19:00
Day 2 => 08:00-09:00 | 11:00-12:00
Day 3 => 08:00-09:00 | 17:00-18:00 | 20:00-21:00
Day 4 => 08:00-09:00 | 14:00-16:00 | 17:00-18:00
Day 5 => 08:00-10:00 | 14:00-15:00
Day 6 => 10:00-11:00
如何檢查兩課時間沖突
因為重疊的時間段可能不是簡單的==
比較,所以必須將課程時間段分為開始和結束塊並分別進行處理。 不幸的是,這會導致大量的代碼循環-但是這是不可避免的。
array_walk_recursive()
用於准備您的輸入數據。 根據設計,該函數僅迭代$sched
的“葉節點”-這意味着$v
永遠不會是數組,它將始終是時間跨度的字符串。 該函數也是“深度忽略的”,因此正確修改原始$sched
數據的唯一方法是使$v
通過引用進行修改(請參閱: &$v
)。
數據重組后,就該開始循環了。 一系列3個連續的循環遍歷“目標” Class和Day子數組以進行比較。 另外兩個循環用於訪問所有其他類的同一天子數組(句點)。 早期的代碼會再次構建實現的array_walk_recursive()
以減少總循環,但這並不是最佳實踐,因為使用帶break(2)
的早退出的foreach循環可節省迭代次數並提高效率。
假設某些類可能沒有一天的句點,我進行了一天檢查,以確保我的方法不會基於缺少的Day子數組而導致“通知/警告”。
代碼:( 演示 )
$sched=[
'Class A'=>[
'Day 1'=>['10:00-11:00','11:00-12:00','13:00-15:00','20:00-21:00'],
'Day 2'=>['12:00-13:00','14:00-15:00'],
'Day 3'=>['08:00-09:00','16:00-17:00','18:00-19:00'],
'Day 4'=>['10:00-11:00','12:00-14:00','14:00-16:00'],
'Day 5'=>['08:00-10:00','13:00-15:00'],
'Day 6'=>['08:00-09:00','10:00-11:00']
],
'Class B'=>[
'Day 1'=>['09:30-10:30','17:00-19:00'],
'Day 2'=>['08:00-09:00','11:00-12:00'],
'Day 3'=>['08:00-09:00','17:00-18:00','20:00-21:00'],
'Day 4'=>['08:00-09:00','14:00-16:00','17:00-18:00'],
'Day 5'=>['08:00-10:00','14:00-15:00'],
'Day 6'=>['10:00-11:00']
],
'Class C'=>[
'Day 1'=>['12:00-14:00']
]
];
// Preparation: Split the dashed time spans into chunked subarrays containing start and end times
// e.g. $sched['Class A']['Day 1'][['10:00','11:00'],['17:00','19:00']]
array_walk_recursive($sched,function(&$v){$v=explode('-',$v);});
// Comparisons:
foreach($sched as $class=>$days){
$other_classes=array_diff_key($sched,[$class=>'']); // same array without target class
foreach($days as $day=>$spans){
//echo "\n\n$class, $day";
foreach($spans as $period=>$span){
//echo "\nchecking {$span[0]} & {$span[1]}";
foreach($other_classes as $other_class=>$other_days){
if(isset($other_days[$day])){ // this avoids Notices/Warning about non-existent day in class
foreach($other_days[$day] as $other_period=>$other_span){ // compare other classes on same day
//echo "\nversus {$other_span[0]} & {$other_span[1]}";
if(($span[0]>=$other_span[0] && $span[0]<$other_span[1]) || ($span[1]<=$other_span[1] && $span[1]>$other_span[0])){
$result[]="Clash: $class,$day#".++$period.": {$span[0]}-{$span[1]} vs $other_class,$day#".++$other_period.": {$other_span[0]}-{$other_span[1]}";
break(2); // no need to further check this $span for clashes
}
}
}
}
}
}
}
echo implode("\n",$result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.