检查来自数据库的发布日期是否早于 1,2,3,4 天并采取措施


Check if post from database date is older then 1,2,3,4 days and take action

我正在尝试检查存储在数据库中的帖子是否分别早于 1、2、3 天,最后是 4 天。

存储所有帖子的表有一个日期字段。我有一个检索日期的查询,然后我尝试检查日期是否分别早于 1、2、3 和 4 天,并根据结果我想在页面上移动帖子。

我有以下几点:

foreach($this->getArticleData() as $i)
{
    if(strtotime($i['date']) > strtotime('-1 day'))
    {
        $this->priority = '0.9';
    }
    elseif(strtotime($i['date']) > strtotime('-2 day'))
    {
        $this->priority = '0.8';
    }
    elseif(strtotime($i['date']) > strtotime('-3 day'))
    {
        $this->priority = '0.7';
    }
    else(strtotime($i['date']) > strtotime('-4 day'))
    {
        $this->priority = '0.6';
    }
}

我认为代码无法正常工作。在某些情况下,优先级是错误的。我正在使用 srttotime() 函数,有没有另一种更可靠的方法可以做到这一点?

Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

您的数据库使用 -'s,您确定这是对的?无论如何,更充分的代码方式是:

foreach ( $this->getArticleData() as $i ) {
    for ( $x = 1; $x < 10; $x++ ) {
        if ( strtotime ( $i [ 'date' ] ) > strtotime ( '-'. $x ." day" ) ) {
            $this->priority = '0.'. 10 - $i;
        }
    }
}

翻转你的>。您正在检查日期是否大于/更新于指定时间。您还需要翻转if语句,因为您要检查最新到最旧。4 天前的帖子也是 1 天前的帖子,将被第一个区块捕获。

我更喜欢使用优先级映射并DateTime

$list = array(
  array( 'date' => '2014-12-14' ) ,
  array( 'date' => '2014-12-15' ) ,
  array( 'date' => '2014-12-14' ) ,
  array( 'date' => '2014-12-11' ) ,
  array( 'date' => '2014-12-14' ) ,
  array( 'date' => '2014-12-13' ) ,
);
# maps days to priority
$priorities = array(
  1 => 0.9,
  2 => 0.8,
  3 => 0.7,
  4 => 0.6
);
$currentDate = new DateTime();
foreach( $list as $i ) {
  $dateTime = new DateTime( $i['date'] );
  $diff = $currentDate->diff( $dateTime );
  $days = $diff->format( '%d' );
  if( isset( $priorities[ $days ] ) ){
    echo 'Date is: ' . $i['date'] . "| Difference is : " . $days . "| Priority is: " . $priorities[ $days ]. "<br/>";
  }
}

结果:

Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-11| Difference is : 4| Priority is: 0.6
Date is: 2014-12-14| Difference is : 1| Priority is: 0.9
Date is: 2014-12-13| Difference is : 2| Priority is: 0.8