2016-11-07 207 views
-1

我有一段时间在PHP函数,我用它来返回,如果用户在线或用户最后一次看到。如何解决Timeago错误

function tj_online_last($ptime) { 
    $estimate_time = time() - strtotime($ptime); 
    // if time diff is less than 1 minute then user is online 
    if ($estimate_time < 60) { 
     return 'online'; 
    } 
    $condition = array(
       12 * 30 * 24 * 60 * 60 => 'year', 
       30 * 24 * 60 * 60  => 'month', 
       24 * 60 * 60    => 'day', 
       60 * 60     => 'hour', 
       60      => 'minute', 
       1      => 'second', 
    ); 
    foreach($condition as $secs => $str) { 
     $d = $estimate_time/$secs; 
     if ($d >= 1) { 
      $r = round($d); 
      return $r.' '.$str.($r > 1 ? 's' : '').' ago'; 
     } 
    } 
} 

现在这里的问题在这里,当用户第一次没有登录到他的帐户的时间值是'NULL'。我想回到'永远',而不是'48年前'令人讨厌的,因为我无法处理错误。

+0

然后'回“从来没有”;',什么是问题? –

回答

0

尝试...... 当用户第一次登录,然后它的最后一项为空,所以你需要检查条件if截止日期为空thenreturn 'never';

function tj_online_last($ptime) { 
    if(strtotime($ptime) <= 0){ 
     return 'never'; 
    } 
    $estimate_time = time() - strtotime($ptime); 
    // if time diff is less than 1 minute then user is online 
    if ($estimate_time < 60) { 
     return 'online'; 
    } 
    $condition = array(
       12 * 30 * 24 * 60 * 60 => 'year', 
       30 * 24 * 60 * 60  => 'month', 
       24 * 60 * 60    => 'day', 
       60 * 60     => 'hour', 
       60      => 'minute', 
       1      => 'second', 
    ); 
    foreach($condition as $secs => $str) { 
     $d = $estimate_time/$secs; 
     if ($d >= 1) { 
      $r = round($d); 
      return $r.' '.$str.($r > 1 ? 's' : '').' ago'; 
     } 
    } 
} 
+0

请详细解释答案,说明你的代码如何工作以及他犯了什么错误。 –

+0

谢谢先生,正是我所需要的,它按预期工作。我从来没有这样想过 –

+0

您的欢迎..;) –