我正试图在聊天中显示"{number}{unit of time}ago"。然而,当我期待类似"2分钟前"的东西时,我看到的却是"45年"。
没有人有答案?
这是脚本:
<?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>";
}
?>
我该怎么做才能让这个功能正常工作?
-
你必须提取日期:
$tm = mysql_query("SELECT timestamp AS t FROM logs ORDER by id ASC")->fetch_assoc()['t']; //obviously, check the size before you fetch
-
您可能想要使用
strtotime()
,例如:$dif = $cur_tm-strtotime($tm);
-
$dif
将以毫秒为单位。 -
你在用循环和数组做什么?太令人困惑了。