简体   繁体   English

使用PHP如何从mysql检索多个日期范围并以日期数组形式返回

[英]With PHP How to retrieve multiple Date Ranges from mysql and return as Array of Dates

Table in mySQL holds hotel reservations for next few years. mySQL中的表可保存未来几年的酒店预订。

Each row contains id, start_date, end_date and status. 每行包含ID,开始日期,结束日期和状态。 the start_date contains a date type which represents the check-in date and the end_date is the checkout date. start_date包含代表入住日期的日期类型,而end_date是退房日期。

I would like to retrieve an array of individual dates so that I can loop through one year calendar and display the dates for next year that are free and which are reserved. 我想检索单个日期的数组,以便循环浏览一年的日历并显示下一年的日期,这些日期是免费的和保留的。

Since the hotel can rent out the room again on the end_date since checkout is early, the end_date itself doesn't need to be included. 由于酒店可在结帐日期较早时在end_date再次出租房间,因此end_date本身不需要包括在内。

example

ID | start_date |  end_date  | status

1  | 03/15/2014 | 03/18/2014 |  Paid
2  | 05/22/2014 | 05/25/2014 |  Deposit
3  | 08/12/2014 | 08/13/2014 |  Paid

and to array: 和数组:

 $months_arry = array(1 => '03/15/2014', 1 => '03/16/2014', 1 => '03/17/2014',
 1 => '05/22/2014', 1 => '05/23/2014', 1 => '05/24/2014', 1 => '08/12/2014');

Since all 12 months of the calendar are displayed vertically on the same page it would be easiest to just check each date against the array to know if it should be green for vacant or red for occupied. 由于日历的所有12个月都垂直显示在同一页面上,因此最简单的方法是仅对数组中的每个日期进行检查,以了解是空的还是空的。

In asp 3.0 on sql server i would have just created a record set rs with " 在sql server上的asp 3.0中,我将创建一个带有“

SELECT start_date, end_date from HotelBookings where start_date >= '2013-12-31'
 AND enddate <= '2015-01-01' ORDER BY start_date ASC"

then a .. do until rs.EOF loop .. inside the 然后..做直到rs.EOF循环..

loop i would retrieve the start_date and end_date and loop them until the two are equal while adding + 1 to the start_date while building the array of individual dates. 循环我将检索start_date和end_date,并循环它们直到两个相等,同时在构建单个日期数组时将start_date加+1。

i found this example while looking for answer but it looks ugly and not elegant 我在寻找答案时找到了这个例子,但是看起来很丑,而且不优雅

<?php
// Make a MySQL Connection
$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result)){
    echo $row['name']. " - ". $row['age'];
    echo "<br />";
}
?>

Be careful with a loop that contains an SQL statement in its body, as the SQL will run n times, where n is the number of times the loop body executes. 小心在其主体中包含 SQL语句的循环,因为SQL将运行n次,其中n是循环主体执行的次数。 That's potentially quite inefficient. 这可能效率很低。

The DateTime object can be your friend here. DateTime对象可以在这里成为您的朋友。

// note that an array with the same key pointing to more than one value will have its values override eachother.
// array(1 => 'foo', 1 => 'bar') is generally not a good idea.
$months_array = array('03/15/2014', '03/16/2014', '03/17/2014', '05/22/2014', '05/23/2014', '05/24/2014', '08/12/2014');

// covert dates to check to DateTimes so that we can perform comparisons on them
$to_check_array = array_map(function ($value) { return new DateTime($value); } , $months_array);

// get all taken date ranges
$result = mysql_query("SELECT `start_date`, `end_date` FROM `date_table`");

// loop over all taken date ranges
while ($row = mysql_fetch_row($result))
{
  // convert dates to DateTimes to perform comparisons on them
  $start_date = new DateTime($row[0]);
  $end_date   = new DateTime($row[1]);

  // check each date against all taken ranges
  foreach ($to_check_array as $cur)
  {
    if ($cur >= $start_date and $cur < $end_date)
    {
      $taken = $cur->format('m/d/Y');
      echo "{$taken} is taken.<br>";
    }
  }
}

I think that should solve your problem. 我认为应该可以解决您的问题。 As for elegance, well, elegance is not exactly abundant in PHP. 至于优雅,在PHP中优雅并不完全丰富。 It's a language that's sort of been mish mashed together by many people from many backgrounds. 这是一种来自许多背景的人融合在一起的语言。 It's a nice and simple, ever-evolving language, but not one I would call elegant. 这是一门优美而又简单,不断发展的语言,但我称之为优雅。 If you need to use PHP and are looking for some elegance in your web apps, I would recommend a framework like CodeIgniter or Laravel. 如果您需要使用PHP并在Web应用程序中寻求一些优雅,我建议您使用CodeIgniter或Laravel之类的框架。 The latter especially is quite elegant. 后者尤其优雅。

Also, be careful using the old mysql_ functions, as those are being removed from coming versions of PHP. 另外,请小心使用旧的mysql_函数,因为这些函数将从即将发布的PHP 版本删除 You might want to look into mysqli or PDO. 您可能需要研究mysqli或PDO。

Even though this isn't really the answer (and I won't mark it as one) here is how I solved the problem. 即使这并不是真正的答案(我不会将其标记为一个),这也是我解决问题的方法。

I was hoping there is a way to do this without having to do all these loop within loops and just to directly get the end result (an array of dates) from the mysql 我希望有一种方法可以执行此操作,而不必在循环中执行所有这些循环,而只是直接从mysql中获取最终结果(日期数组)

This will select all date ranges from the mysql when the hotel room is booked and then convert the ranges to single dates in an array. 预订酒店房间时,它将从mysql中选择所有日期范围,然后将范围转换为数组中的单个日期。 So the end result is a unique sorted array of all dates after today's date when the hotel room has been reserved. 因此,最终结果是在预订酒店房间之后的所有日期之后的所有日期的唯一排序数组。

<?php
$current_date_t = date('Y-m-d');
$current_date = new DateTime($current_date_t);

// Make a MySQL Connection

$query = "SELECT from_date, to_date FROM t_booking_data where from_date >= '" . $current_date . "' ";

$result = mysql_query($query) or die(mysql_error());
$booked_days_array = array();

while ($row = mysql_fetch_array($result))
{
    $startDate_t = $row['from_date'];
    $startDate = new DateTime($startDate_t);
    $endDate_t = $row['to_date'];
    $endDate = new DateTime($endDate_t);

    while ($startDate < $endDate)
    {
        array_push($booked_days_array, $startDate->format('Y-m-d'));
        $startDate->modify('+1 day');
    }
}
$booked_days_array = array_unique($booked_days_array);
sort($booked_days_array);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从带有序列化日期的数组中查找间隔日期范围,在php中 - Find gap date ranges from array with serialized dates in php 返回多个日期范围之间的所有日期 - Return all dates between multiple date ranges PHP如何从检查数组中多个日期范围的函数中获取值 - PHP How to get value from function that checks between multiple date ranges in array MySQL(+ php)存储,检索和显示日期范围的正确方法 - Mysql (+php) Right approach to store, retrieve and show date ranges 如何在 PHP 中的日期数组中从最近的日期到最远的日期对日期进行排序 - How to sort dates from closest date to the furthest in an array of dates in PHP 从PHP中的文本中提取日期,时间和日期范围 - Extract dates, times and date ranges from text in PHP PHP / MySQL从多个WHERE和范围中选择 - PHP/MySQL select from with multiple WHERE and ranges 从PHP和Mysql禁用jquery datepickers中给定范围内的日期 - Disable Dates within given ranges in jquery datepickers from PHP and Mysql 检查日期是否在 PHP 中的多维数组中的多个日期范围之间 - Checking if a date is in between multiple date ranges in a multidimensional array in PHP 如何从PHP和MySQL数据库获取等于当前日期的日期? - How to get dates from PHP and MySQL database that is equal to the current date?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM