Php foreach 在时隙间隔中循环,如果间隔空闲则仅返回四分之一时间

标签 php mysql laravel eloquent

我有一个 mySQL 表“timeslots”,其中包含“intervals”和“reserved”列。我如何循环遍历它并仅返回 15 分钟的间隔,但必须保留“剪切”15 分钟的间隔 = 0。例如,我应该循环遍历“间隔”列并返回 08:15:00 但跳过08:00:00 因为 08:08:00 间隔被保留(保留列 = 1),我也应该跳过间隔 08:45:00 因为 08:53:00 被保留 = 1。我已附上表格的图像对于这个问题。

我几天来一直在尝试寻找解决方案,但没有成功。

enter image description here

public function getTimeSlots($app)
{
$timeslots = Timeslot::where('app', '=', $app)->where('reserved', '=', 0)->orderBy('intervals', 'ASC')->get();
    $timeslotlist = array();

    foreach ($timeslots as $timeSlot) {

        $timeslotlist[] = array(
            'id' => $timeSlot['id'],
            'app' => $timeSlot['app'],
            'intervals' => $timeSlot['intervals'],
            'reserved' => $timeSlot['reserved'],
        );
    }
   return json_encode($timeslotlist);
}

最佳答案

您首先需要获得预留的插槽。然后在循环中检查该槽位是否有下一个保留槽位。

public function getTimeSlots($app)
{
$reservedSlots = Timeslot::where('app', '=', $app)->where('reserved', '=', 1)->orderBy('intervals', 'ASC')->get();
$timeslots = Timeslot::where('app', '=', $app)->where('reserved', '=', 0)->orderBy('intervals', 'ASC')->get();
    $timeslotlist = array();

    foreach ($timeslots as $timeSlot) {
        $haveNextReservedSlot = array_filter($reservedSlots, function($v) use($timeSlot){ 
             $start_date = new DateTime($timeSlot['date'].' '.$timeSlot['intervals']);
             $since_start = $start_date->diff(new DateTime($v['date'].' '.$v['intervals']));
             return $since_start->i < 15; //if difference less than 15 min
      });
        if($haveNextReservedSlot) continue;

        $timeslotlist[] = array(
            'id' => $timeSlot['id'],
            'app' => $timeSlot['app'],
            'intervals' => $timeSlot['intervals'],
            'reserved' => $timeSlot['reserved'],
        );
    }
   return json_encode($timeslotlist);
}


关于Php foreach 在时隙间隔中循环,如果间隔空闲则仅返回四分之一时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545987/

相关文章:

php - 如何隐藏显示在 HTML 上的回显结果?

mysql - 使用 Node、Express、Knex 和 Bookshelf 控制对 MySQL 中数据的访问

mysql - 如何执行MySQL order by x where (x=col3 if col3!=null, else x=col2)?

laravel - 为什么 Pagination laravel 会忽略请求 - skip, take

php - 使用 Ajax 和 Jquery 设置 Iframe 目标?

php - 无法创建 MySQL 存储过程

mysql - Wordpress 自定义 SQL 以获取具有给定元值的三个帖子

node.js - 为什么 webpack 会多出 10,000 行?

php - Laravel Eloquent : How to generate a fake column in a Json response?

javascript - PHP在谷歌地图上显示多维数组值