You need to enable JavaScript to run this app. PHP实现MySQL时间戳发布时长显示异常:输出变量名而非实际值
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现MySQL时间戳发布时长显示异常:输出变量名而非实际值

解决PHP时间显示变量名而非实际时长的问题

嘿,我一眼就看出问题所在啦!你代码里那些返回语句用了单引号,PHP在单引号包裹的字符串中不会解析变量,只会把变量名当作普通文本输出,这就是为什么你看到的是$minutes minutes ago而不是实际计算出的分钟数。

具体修复方法

你只需要把所有包含变量的返回语句,从单引号换成双引号,或者用字符串拼接的方式即可:

错误示例:

return '$minutes minutes ago';

正确写法(二选一即可):

  1. 使用双引号(PHP会自动解析双引号内的变量):
return "$minutes minutes ago";
  1. 使用字符串拼接:
return $minutes . ' minutes ago';

修改后的完整函数代码

另外,我发现你的函数里有一段多余的数据库查询代码——既然已经把$post_datetime作为参数传入了,完全不需要再去查数据库,直接用这个参数计算就行,我帮你把这部分冗余代码删掉了:

<?php
date_default_timezone_set('Africa/Harare');

function get_timeago($post_datetime){
    $timeago = $post_datetime;
    $current_time = time();
    $time_difference = $current_time - $timeago;
    
    $seconds = $time_difference;
    $minutes = round($seconds / 60);
    $hours = round($seconds / 3600);
    $days = round($seconds / 86400);
    $weeks = round($seconds / 604800);
    $months = round($seconds / 2629800); // ((365 + 365 + 365 + 366)/4/12) * 24 * 3600
    $years = round($seconds / 31557600); // $months * 12

    if($seconds <= 60){
        return 'Just Now';
    } else if($minutes <= 60){
        if($minutes == 1){
            return 'a minute ago';
        } else {
            return "$minutes minutes ago";
        }
    } else if($hours <= 60){
        if($hours == 1){
            return 'an hour ago';
        } else {
            return "$hours hrs ago";
        }
    } else if($days <= 7){
        if($days == 1){
            return 'Yesterday';
        } else {
            return "$days days ago";
        }
    } else if($weeks <= 4){
        if($weeks == 1){
            return 'a week ago';
        } else {
            return "$weeks weeks ago";
        }
    } else if($months <= 12){
        if($months == 1){
            return 'a month ago';
        } else {
            return "$months months ago";
        }
    } else if($years == 1){
        return 'a year ago';
    } else {
        return "$years years ago";
    }
}
?>

<span class="description">Shared publicly <i class="fa fa-globe"></i> - <?php echo get_timeago(strtotime($row['post_datetime'])); ?></span>

额外说明

我还调整了调用函数的代码,把PHP代码和HTML标签正确分开了,避免语法错误。现在运行这段代码,就能正常显示实际的流逝时间啦!

内容的提问来源于stack exchange,提问作者Tinashe Chaterera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:49:45