mySQL 中的表保存 future 几年的酒店预订。
每一行包含 id、start_date、end_date 和 status。 start_date 包含代表入住日期的日期类型,end_date 是结帐日期。
我想检索一组单独的日期,以便我可以遍历一年的日历并显示下一年的免费日期和保留日期。
由于结账提前,酒店可以在 end_date 再次出租房间,因此不需要包括 end_date 本身。
例子
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
和数组:
$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');
由于日历的所有 12 个月都垂直显示在同一页上,因此最简单的方法是根据数组检查每个日期,以了解它应该是绿色表示空闲还是红色表示占用。
在 sql server 上的 asp 3.0 中,我会用“
创建一个记录集 rsSELECT start_date, end_date from HotelBookings where start_date >= '2013-12-31'
AND enddate <= '2015-01-01' ORDER BY start_date ASC"
然后 a .. do until rs.EOF loop .. inside
循环我将检索开始日期和结束日期并循环它们直到两者相等,同时在构建单个日期数组时将 + 1 添加到开始日期。
我在寻找答案时发现了这个例子,但它看起来很丑而且不优雅
<?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 />";
}
?>
最佳答案
小心循环体中包含 SQL 语句,因为 SQL 将运行 n 次,其中 n 是循环体执行的次数。这可能效率很低。
DateTime 对象可以成为您的 friend 。
// 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>";
}
}
}
我认为这应该可以解决您的问题。至于优雅,好吧,优雅在 PHP 中并不十分丰富。这是一种被来自不同背景的许多人混合在一起的语言。这是一种很好的、简单的、不断发展的语言,但不是我称之为优雅的语言。如果您需要使用 PHP 并且希望在您的 Web 应用程序中寻找一些优雅的东西,我会推荐一个像 CodeIgniter 或 Laravel 这样的框架。后者尤其优雅。
另外,小心使用旧的 mysql_
函数,因为那些 are being removed from coming versions的PHP。您可能想查看 mysqli 或 PDO。
关于php - 使用 PHP 如何从 mysql 检索多个日期范围并作为日期数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18632802/