我有一个存储ID的数组,每个ID都有一个包含起始值和结束值的数组。我的目标是检查起始值是否小于数组中它前面的项的结束值。
这有效但我的循环并不关心ID,我需要一种方法来执行此ID
这是我的数组的样子:
Array
(
[892] => Array
(
[41] => Array
(
[0] => Array
(
[start] => 0930
[end] => 1200
)
)
)
[897] => Array
(
[41] => Array
(
[0] => Array
(
[start] => 1000
[end] => 1230
)
)
)
[898] => Array
(
[41] => Array
(
[0] => Array
(
[start] => 1100
[end] => 1300
)
)
)
[901] => Array
(
[52] => Array
(
[0] => Array
(
[start] => 0930
[end] => 1030
)
)
)
[903] => Array
(
[52] => Array
(
[0] => Array
(
[start] => 0930
[end] => 1030
)
)
)
[904] => Array
(
[41] => Array
(
[0] => Array
(
[start] => 1000
[end] => 1230
)
)
)
)
这就是我的循环:
$foundOverlap = false;
$prevEnd = null;
foreach($slots as $s){
$startHour = $s[0]['start'];
$endHour = $s[0]['end'];
echo $startHour . '<br>';
echo $endHour . '<br>';
if($prevEnd !== null && $startHour < $prevEnd){
$foundOverlap = true;
$counter++;
}
if($foundOverlap){
echo 'overlap <br>';
}else{
echo 'no overlap <br>';
}
$prevEnd = $endHour;
}
结果我得到没有重叠(好),重叠(好),重叠(好),重叠(坏!)这应该没有重叠。但它说重叠,因为它检查前一个数组项目并不关心attractieID是什么...
任何人都知道如何解决这个问题吗?
我会非常感激!!
提前致谢!
答案 0 :(得分:0)
来自Muhammad Kashif Abbasi的评论我想给你一个解决方案
试试此代码
$foundOverlap = false;
$prevEnd = null;
$preID = null;
foreach($slots as $s){
$startHour = $s[0]['start'];
$endHour = $s[0]['end'];
$currentID = $s['attractieID']; //got the current attractieID
echo $startHour . '<br>';
echo $endHour . '<br>';
if($prevEnd !== null && $startHour < $prevEnd && $currentID == $preID){ // checked current id and previous id
$foundOverlap = true;
$counter++;
}
if($foundOverlap){
echo 'overlap <br>';
}else{
echo 'no overlap <br>';
}
$foundOverlap = false; //reseted $foundOverlap
$prevEnd = $endHour;
$preID = $currentID; //set the current id as previous id
}
答案 1 :(得分:0)
检查出来
$result = [];
foreach($array as $element) {
if(!isset($result[$element['attractiveID']])) {
$result[$element['attractiveID']]['overlap'] = false;
$result[$element['attractiveID']]['prevHour'] = $element[0]['end'];
continue;
}
if($element[0]['start'] < $result[$element['attractiveID']]['prevHour']) {
$result[$element['attractiveID']]['overlap'] = true;
}
$result[$element['attractiveID']]['prevHour'] = $element[0]['end'];
}
和数组传递:
$array = [
[
'attractiveID' => 41,
[
'start' => 930,
'end' => 1200
]
],
[
'attractiveID' => 41,
[
'start' => 1000,
'end' => 1230
]
],
[
'attractiveID' => 41,
[
'start' => 1100,
'end' => 1300
]
],
[
'attractiveID' => 52,
[
'start' => 1000,
'end' => 1230
]
],
];