在while循环中有日期比较的奇怪行为 [英] Strange behaviour in a while loop with a date compare in PHP
问题描述
我正在尝试创建一个简单的while循环,该循环从PHP中的数据库中提取一个关联数组。本质上,我想对从数据库中提取的日期与当前日期进行比较。这里是要抓住的地方。不同部分(表中表示)有不同的截止日期。因此,我需要通过减去某些天数来修改从数据库中提取日期的日期。我用不同的变量完成了此操作,但得到了一些奇怪的结果,这些结果与我指定的结果不同。我想念什么吗?
Hi I am trying to create a simple while loop that pulls an associative array from a database in PHP. In essence I want to then do a compare on the date pulled from the database with the current date. Here is the catch. Different sections (represented in a table) have different deadlines. So I need to modify the pulled date from the database by subtracting certain amounts of days. I have done this with different variables but I get some weird results which are not the ones I have specified. Am i missing something?
$today = date("Y-m-d")
while ($query_row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$date = $query_row['DueDate'];// this is the due date from the server
$duedate = $date->format('d-m-Y'); // to output in table
$compare1 = $date;
$compare2 = $date;
$compare3 = $date;
$compare4 = $date;
$compare1->modify('-4 days');
$compare2->modify('-3 days');
$compare3->modify('-2 days');
$compare4->modify('-1 day');
echo $today.' today <br/>';
//just for debugging
echo $date ->format('Y-m-d').' due date <br/>';
echo $compare1->format('Y-m-d').' minus 4 date <br/>';
if ( $today >= $compare1 )
{
$Triginsert = 'style="background-color: #ff0000;"';
}
else
{
$Triginsert = '';
}
}
您可以看到当前日期是否大于或等于比较日期,该日期应该是从服务器提取的日期-4天,然后应将其变为红色,否则它什么都不做。。
As you can see if the current date is greater than or equal to the compared date which should be the date pulled from server - 4 days then it should turn the block red else it should do nothing..
任何帮助都会大。
谢谢
推荐答案
发生的事情是,由于对象是由在php 5+中引用,您所有的$ compare变量都是对同一原始$ date对象的引用。因此,您要反复修改同一个而不是创建4个单独的对象。参见 http://www.php.net/manual/en/language。 oop5.references.php 。
您想要的是:
what's happening is that since objects are assigned by reference in php 5+, all your $compare variables are references to the same original $date object. So you are modifying the same one repeatedly instead of creating 4 separate ones. See http://www.php.net/manual/en/language.oop5.references.php . What you want instead is:
$compare1 = clone $date;
$compare2 = clone $date;
etc.
BTW当您使用var_dump($ query_row ['DueDate' ])?我以为它已经是一个日期对象,否则-> modify()调用将立即出错,并且您说的是您得到的是怪异的行为,而不是错误消息,但是其他一些答案都假定$ query_row [' DueDate']是一个字符串,因此我想再次检查。
BTW what do you get when you var_dump($query_row['DueDate']) ? I was assuming it was already a date object, otherwise the ->modify() calls would error immediately, and you were saying you were getting weird behavior rather than an error message, but some of the other answers are assuming that $query_row['DueDate'] is a string so I wanted to double check.
这篇关于在while循环中有日期比较的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!