2015-02-11 59 views
-1

我想在我的聊天中显示“{number} {unit-of-time} ago”。但是,当我期待“2分钟前”之类的东西时,我会看到“45年”。xx前面的功能不起作用

没有人有答案?

下面是脚本:

<?php 
$con = mysql_connect("localhost", "user", "pword"); 
mysql_select_db('chat', $con); 
$result1 = mysql_query("SELECT * FROM logs ORDER BY id ASC"); 

$tm = mysql_query("SELECT timestamp FROM logs ORDER BY id ASC"); 

function _ago($tm, $rcs = 0) 
{ 
    $cur_tm = time(); 
    $dif = $cur_tm - $tm; 
    $pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year'); 
    $lngh = array(1, 60, 3600, 86400, 604800, 2630880, 31570560); 
    for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif/$lngh[$v]) <= 1); $v--) ; 
    if ($v < 0) $v = 0; 
    $_tm = $cur_tm - ($dif % $lngh[$v]); 

    $no = floor($no); 
    if ($no <> 1) $pds[$v] .= 's'; 
    $x = sprintf("%d %s ", $no, $pds[$v]); 
    if (($rcs == 1) && ($v >= 1) && (($cur_tm - $_tm) > 0)) $x .= time_ago($_tm); 
    return $x; 
} 

$timeagochat = _ago($tm, $rcs = 0); 

while ($extract = mysql_fetch_array($result1)) { 
    echo "<p class='show_message'><span class='uname'>" . $extract['username'] . "</span> <span class='time'>" . $timeagochat . " </span><br><span class='msg'>" . $extract['msg'] . "</span></p><br>"; 
} 

?> 

我能做些什么让这个功能的工作?

+1

为什么它“当然错”?对我们来说,读者并不那么明显。 – GolezTrol 2015-02-11 18:11:13

+0

我写了2分钟前的消息,它显示'45年'.. – Intera 2015-02-11 18:12:24

+0

可能重复的[如何计算“时间前”在PHP中](http://stackoverflow.com/questions/11481737/how-to-calculate在PHP中) – dave 2015-02-11 18:16:35

回答

0
  1. 你要获取日期:

    $tm = mysql_query("SELECT timestamp AS t FROM logs ORDER by id ASC")->fetch_assoc()['t']; //obviously, check the size before you fetch

  2. 你可能想使用strtotime()因此,例如:

    $dif = $cur_tm-strtotime($tm);

  3. $dif将在毫秒。

  4. 你在做什么循环和数组?太混乱。

5.为什么人们继续使用mysql_

+0

它仍然无法正常工作...... :( – Intera 2015-02-11 18:27:41