PHP变量无法解释更新

时间:2018-03-28 14:43:56

标签: php

我确信这是我看不到的愚蠢行为,但是当我觉得不应该这样时,我会有一个变量更新。

$dateholder = "";
$currentdate = "";
$rsresults->MoveFirst();
while (!$rsresults->EOF) {
    $currentdate = $rsresults->fields['newdate'];
    echo "current date: " . $currentdate . "<br>";
    echo "previous date: " . $dateholder . "<br>";
    if($currentdate > $dateholder){
        echo "CURRENT DATE DIFFERENT THAN DATEHOLDER<br><br>";
        $dateholder = $currentdate;
    }
    $rsresults->MoveNext();
}

我从我的数据库中获取日期。如果它与上一个日期不同,我想输出不同的日期。 (按日期排序)。以下是我得到的结果:

current date: 2018-01-22
previous date:
CURRENT DATE DIFFERENT THAN DATEHOLDER

current date: 2018-01-22
previous date: 2018-01-22
current date: 2018-01-23
previous date: 2018-01-23
current date: 2018-01-23
previous date: 2018-01-23
current date: 2018-01-24
previous date: 2018-01-24
current date: 2018-01-24
previous date: 2018-01-24
current date: 2018-01-25
previous date: 2018-01-25

第一个是预期的,但我的dateholder变量如何更新而不回显CURRENT DATE DIFFERENT

2 个答案:

答案 0 :(得分:0)

编辑我

关于问题:

在代码中,分配值时返回的内容不是String而是Object(在注释中确认)。

因此,当$dateholder = $currentdate赋值完成时,$ dateholder引用与$currentdate相同的对象,而不是仅获取当前字符串值。

之后,$currentdate中的任何更改也会更改$datholder,因为它们指向同一个对象。

解决问题:

在执行分配之前转换为(字符串),如此处所述SQL return “variant Object” how to convert to regular data

在你的情况下:

$dateholder = "";
$currentdate = "";
$rsresults->MoveFirst();
while (!$rsresults->EOF) {
    $currentdate = (string) $rsresults->fields['newdate'];
    echo "current date: " . $currentdate . "<br>";
    echo "previous date: " . $dateholder . "<br>";
    if($currentdate > $dateholder){
        echo "CURRENT DATE DIFFERENT THAN DATEHOLDER<br><br>";
        $dateholder = (string) $currentdate;
    }
    $rsresults->MoveNext();
}

答案 1 :(得分:0)

你正在比较字符串而不是像这样的日期

if ( "hi" > "hello" ){
 echo "hello";
}

比较将字符串转换为日期所需的日期然后比较它们

$date1 = strtotime('2018-01-22');
$date2 = strtotime('2018-02-22');

if($date1 < $date2){
  //do somthing 
}