-1

我正在开发一个预订系统,客户最多可以预订 3 个座位。如果他们只预订 1 个座位,这意味着其他 2 个座位值设置为空,当我提交表单时,我会检查它以确保客户不会尝试重复预订同一个座位,如您将在下面的代码,所以如果客户购买 1 个席位,他们会收到一个错误,因为两个席位都等于 null,我该如何解决这个问题?谢谢

if($seat1==$seat2 || $seat2==$seat3 || $seat1==$seat3){
echo("You're trying to book the same seat numerous times, please go back.");
die();
}
4

2 回答 2

1

使用数组。它们可以具有任意数量的值,因此您没有 3 的限制,尽管您仍然可以强制执行它。当你使用它时,你也可以使用一个类。就是图个好玩儿。;)

$mrA = new User("GolezTrol");
$mrB = new User("user1715417");

try {

    $booking = new Booking();
    $booking->bookSeat($mrA, 'A7');
    $booking->bookSeat($mrA, 'A8');
    // $booking->bookSeat($mrB, 'A8'); // Double booking
    $booking->bookSeat($mrB, 'A9');
    $booking->bookSeat($mrA, 'B7');
    // $booking->bookSeat($mrA, 'B8'); // Only 3 seats allowed per user
    $booking->bookSeat($mrB, 'B9');
    // $booking->bookSeat($mrB, 'C7'); // No Seat Left

    var_dump($booking->bookedSeats); // Output Booking

} catch ( Exception $e ) {
    echo $e->getMessage(), PHP_EOL;
}

输出

array
  'GolezTrol' => 
    array
      0 => string 'A7' (length=2)
      1 => string 'A8' (length=2)
      2 => string 'B7' (length=2)
  'user1715417' => 
    array
      0 => string 'A9' (length=2)
      1 => string 'B9' (length=2)

使用的类

class User {
    public $id;

    function __construct($id) {
        $this->id = $id;
    }

    function __toString() {
        return $this->id;
    }
}

class Booking {
    public $bookedSeats = array();
    public $seatUsed = array();
    private $maxSeat = 5;
    private $maxBooking = 3;

    public function bookSeat(User $user, $seat) {
        if (count($this->seatUsed) >= $this->maxSeat) {
            throw new Exception('No Seat Left');
        }

        if (in_array($seat, $this->seatUsed)) {
            throw new Exception('Double booking');
        }

        if (array_key_exists($user->id, $this->bookedSeats)) {
            if (count($this->bookedSeats[$user->id]) >= $this->maxBooking) {
                throw new Exception('Only 3 seats allowed');
            }

            $this->bookedSeats[$user->id][] = $seat;
            $this->seatUsed[] = $seat;
        } else {
            $this->bookedSeats[$user->id] = array();
            $this->bookedSeats[$user->id][] = $seat;
            $this->seatUsed[] = $seat;
        }
    }
}

您可以看到将限制设置为 5 或 8 个席位是多么容易,而无需修改除数字之外的任何内容,而您当前的检查已经很复杂,如果您从 3 增加到 5,它将变得复杂两倍。

于 2012-10-12T22:09:57.797 回答
0

这是显而易见的答案,我会让其他人浮华和嗖嗖:)

if ( $seat1 === $seat2 || $seat1 === $seat3 || ($seat2 !== null && $seat2 === $seat3) )
于 2012-10-12T22:06:12.883 回答