在DB中,也有第26天和第31天,但没有更改为OK。 只得到第3天并更改为OK。
这段代码哪里错了?
代码:
*$from = date("Y-m-01");
$to = date("Y-m-t"); // last day current month
$query = "SELECT date FROM tbl_data WHERE date BETWEEN '$from' AND '$to' order by date DESC";
$result = mysqli_query($mysqli,$query);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$date = date_create_from_format('Y-m-d', $row['date']);
}
$cursor = date_create_from_format('Y-m-d', $from);
$finish = date_create_from_format('Y-m-d', $to);
while ($cursor != $date)
{
echo date_format($cursor,'Y-m-d') . "--- Missed <br>";
date_modify($cursor, '+1 day');
while($cursor == $date)
{
echo date_format($date,'Y-m-d') . "--- OK <br>";
date_modify($cursor, '+1 day');
}
while($cursor > $finish)
{
die();
}
}*
输出:
2016-07-01--- 错过
2016-07-02--- 错过
2016-07-03--- 好的
2016-07-04--- 错过
2016-07-05--- 错过
2016-07-06--- 错过
2016-07-07--- 错过
2016-07-08--- 错过
2016-07-09--- 错过
2016-07-10--- 错过
2016-07-11--- 错过
2016-07-12--- 错过
2016-07-13--- 错过
2016-07-14--- 错过
2016-07-15--- 错过
2016-07-16--- 错过
2016-07-17--- 错过
2016-07-18--- 错过
2016-07-19--- 错过
2016-07-20--- 错过
2016-07-21--- 错过
2016-07-22--- 错过
2016-07-23--- 错过
2016-07-24--- 错过
2016-07-25--- 错过
2016-07-26--- 错过
2016-07-27--- 错过
2016-07-28--- 错过
2016-07-29--- 错过
2016-07-30--- 错过
2016-07-31--- 错过
最佳答案
您的问题很难理解,但据我了解,您正在尝试检查是否有迭代日期的记录。
您错过的要点是,您仅在 $date
变量上存储单个日期。澄清;
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$date = date_create_from_format('Y-m-d', $row['date']);
}
/* at this point of code, your variable $date is exactly equal to 2016-07-03
* because you sorted all existing dates in descending order and last record is 2016-07-03
*/
在此代码部分之后,您的“OK”检查仅对“2016-07-03”有效。要更正代码,您应该使用数组来存储所有日期并使用 in_array()
函数来检查是否存在。
另一种选择是在更改 ORDER BY 方向后在 while 循环内应用这些过程。如果两个连续的记录不是连续的天,您将填补这些间隙(第二级)迭代。
关于PHP MYSQL 日期范围错过的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633663/