我有一个SQL查询返回:

start_time of the event  |  end time of the event   |   duration of the event


在我的php代码中,我遍历结果,并检查是否可以在现有事件之间插入另一个事件-基本上,我正在检查一个事件结束与上一个事件开始之间的时间差是否大于上一个事件的持续时间-如果是,则将其结束日期保存为新创建的事件的开始日期。

我创建了一个php查询,它在执行sql SELECT查询后立即发生:

if($q3->rowCount()>0)
{
    $check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
    $arr = array();
    foreach ($check3 as $row) {
        $arr[] = $row;
    }

    $firstRow = $arr[0];

        for($i=0; $i < count($arr); $i++) {
            $current_row = $arr[$i];
            $next_row    = $arr[$i+1];

            if (($next_row["begin_date"] - $current_row["end_date"]) >= $duration){
                $found_timestamp_for_new_event = $current_row["end_date"];
                break;
            }

        }

    $last_element = ($arr[count($arr) - 1]['end_date']);
    if($end_timestamp - $last_element >= $duration){
        $found_timestamp_for_new_event = $last_element;

    }
 }


但是,当我运行它时,我得到警告:

Notice Undefined offset: 1 in ...


并且警告在$next_row = $arr[$i+1];行中。
我认为发生这种情况是因为在某些情况下查询不返回更多事件,因此它看不到$arr[$i+1]

我该如何解决?

最佳答案

当您到达数组的最后一个元素时,将引发错误。使用IF语句检查是否确实存在另一个元素。

if ( $i < count($arr)-1 ) {
    // THERE IS AT LEAST ANOTHER ROW AFTER THIS
    $next_row = $arr[$i+1];
} else {
    // THIS IS THE LAST ROW, DO SOMETHING ELSE HERE
}

08-06 03:03