【发布时间】:2015-08-23 05:15:15
【问题描述】:
数据摘要
我有以下数据,现有事件的 $existing_events 数组和新事件的请求($requested_start 和 $requested_end)。通常从 SQL 中提取,但我在这里用静态数组复制了这个问题:
$existing_events = array(
0 => array(
'time_start' => '2015-09-05 11:30:00',
'time_end' => '2015-09-05 18:45:00'
),
1 => array(
'time_start' => '2015-09-05 07:15:00',
'time_end' => '2015-09-05 10:30:00'
)
);
$requested_start = strtotime('2015-09-05 3:30:00 AM');
$requested_end = strtotime('2015-09-05 9:30:00 AM');
结果数组
一个$results 数组,用于跟踪进行了多少次比较('comparison_counter')以及发现了多少冲突('conflicts'):
$results = array(
'conflicts' => 0,
'comparison_counter' => 0
);
FOREACH 循环
最后,在输出 json_encode 的结果之前,foreach 循环使用this logic 将请求的新事件的开始和结束时间与每个预先存在的事件的开始和结束时间进行比较。注意comparison_counter 和conflict 的增量——前者在每次循环运行时运行,而后者仅在其 if 语句中“到达”,当请求的事件时间和当前事件时间之间存在冲突时经过测试。
if (!empty($existing_events)){
foreach ($existing_events as $existing_event){
$existing_start = strtotime($existing_event['time_start']);
$existing_end = strtotime($existing_event['time_end']);
$results['comparison_counter']++;
if ($requested_start > $existing_end) {
break;
} elseif ($requested_end < $existing_start) {
break;
} else {
$results["conflicts"]++;
}
}
}
echo json_encode($results);
exit;
实际反应
不过,我收到的信息表明 foreach 循环似乎只执行了一次,尽管我的 $existing_events 数组中有两个项目。以下是我收到的上述数据:
comparison_counter: 1
conflicts: 0
对比我的期望:
comparison_counter: 2
conflicts: 1
奇怪的是,只要我对 11:30 start-time 进行以下更改(以尝试与 both 事件重叠):
$requested_end = strtotime('2015-09-05 11:30:00 AM');
...comparison_counter 现在可以使用了。我现在收到以下信息:
comparison_counter: 2
conflicts: 2
我的问题
根据我传递的数组中的内容,为什么 foreach 循环不能正常运行?我希望它每次触发时至少会击中它的$results['comparison_counter']++;。
【问题讨论】:
-
$requested_start 和 $requested_end 的值具体是什么?我认为您的比较不会达到您的预期。
-
@SetSailMedia - 正在提交的表单数据,然后是 strtotime'd...在这种情况下:requested_start: 1441423800 requested_end: 1441452600
-
它们是日期/时间戳,还是数字 time() 值? nvm 刚刚看到你的编辑
-
第一个查询不是处理所有这些吗(嗯,稍微调整一下)?我不明白第二个查询的意义
-
@Strawberry 你是对的,它可能会。由于我最初拥有完整日期时间格式的两种格式,我想我会先比较这种方式,然后直接通过引用修改数组。为了隔离问题,我们可能会忘记第二个 foreach 循环的存在。第一个是否存在问题,当只有第二个现有事件发生冲突时,它不会抛出冲突标志?谢谢!