首页 > 解决方案 > 从 CodeIgniter 中的数组中删除对象

问题描述

我有这个功能:

public function get_free_courtrooms() {
        $post = file_get_contents('php://input');
        $_POST = json_decode($post, true);

        $date = $this->input->post('date', true);
        $time_start = $this->input->post('time_start', true);
        $time_end = $this->input->post('time_end', true);

        $where = array('date' => $date);
        $reservations = $this->MY_Model->get('reservations', $where);

        $courtrooms = $this->MY_Model->get('courtrooms');

        $output = array(
            'free_courtrooms' => $free_courtrooms
        );

        echo json_encode($output);
        exit();
    }

我需要从 $courtrooms 中删除所有在发送时间($time_start、$time_end)中预订的法庭。

在预订表中,我有:

标签: phparrayscodeigniter-3

解决方案


我将从简单的函数开始检查重叠 2 次:

function isOverlap($s1, $e1, $s2, $e2) {
    return (($s1 > $s2 && $s1 < $e2) || ($e1 > $s2 && $e1 < $e2)
            || ($s1 < $s2 && $e1 > $2) || ($s1 > $s2 && $e1 < $e2));
}

这将是 4 种情况的可视化:

---     |    ---  |   -------   |     ---
  ---   |   ---   |     ---     |   -------

现在只需填充所有繁忙房间的数组:

foreach($reservations as $res) {
    if (isOverlap($time_start, $time_end, $res["start"], $res["end"]))
        $busy_courtrooms[] = $res["id"]; 
}

现在计算所有$courtrooms$busy_courtrooms使用array-diff之间的差异:

$free_courtrooms = array_diff($courtrooms, $busy_courtrooms);

你完成了

我现在不知道你的$reservations数组是如何构建的,但我猜它有“开始”和“结束”属性......


推荐阅读