【问题标题】:xx time ago function doesn't workxx时间前功能不起作用
【发布时间】:2015-02-11 18:09:34
【问题描述】:

我试图在我的聊天中显示“{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>";
}

?>

我该怎么做才能让这个功能发挥作用?

【问题讨论】:

  • 为什么“当然是错的”?对我们来说,不是那么明显的读者。
  • 我在 2 分钟前写了这条消息,它显示“45 年”..

标签: php mysql


【解决方案1】:
  1. 你必须获取日期:

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

  2. 您可能想使用strtotime(),例如:

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

  3. $dif 将以毫秒为单位。

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

5。为什么人们一直使用mysql_!!!

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 2014-04-17
    • 2018-12-26
    • 2017-05-06
    • 2012-12-28
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多