You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将计算得到的相对时间字段合并到JSON查询结果数组中

你只需要在foreach循环计算得到$PostedTime后,将该字段追加到当前遍历的数组项中即可,具体实现代码如下:

foreach($CommentTime as $k => $cmt)
{
    $CreatedAt = $cmt['CreatedAt'];
    $time_ago = (int)$CreatedAt; // 建议转成整型,避免字符串类型时间戳计算出错
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $seconds    = $time_elapsed ;
    $minutes    = round($time_elapsed / 60 );
    $hours      = round($time_elapsed / 3600);
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );

    // 秒数判断
    if($seconds <= 60){
        $PostedTime = "刚刚";
    }
    // 分钟判断
    else if($minutes <=60){
        $PostedTime = $minutes == 1 ? "1分钟前" : $minutes."分钟前";
    }
    // 小时判断
    else if($hours <=24){
        $PostedTime = $hours == 1 ? "1小时前" : $hours."小时前";
    }
    // 补充你未完成的天数判断
    else if($days <=7){
        $PostedTime = $days == 1 ? "1天前" : $days."天前";
    }
    // 周数判断
    else if($weeks <=4){
        $PostedTime = $weeks == 1 ? "1周前" : $weeks."周前";
    }
    // 月数判断
    else if($months <=12){
        $PostedTime = $months == 1 ? "1个月前" : $months."个月前";
    }
    // 年数判断
    else{
        $PostedTime = $years == 1 ? "1年前" : $years."年前";
    }

    // 核心逻辑:追加Time字段到原数组对应项中
    $CommentTime[$k]['Time'] = $PostedTime;
}

// 输出最终JSON,加JSON_UNESCAPED_UNICODE避免中文被转义
echo json_encode($CommentTime, JSON_UNESCAPED_UNICODE);

注意事项

  • 需补全所有时间区间的判断分支,否则超过24小时的时间会出现$PostedTime未定义的问题
  • 如果数据库返回的CreatedAt是字符串类型,强制转为整型可以避免计算异常

内容的提问来源于stack exchange,提问作者sheetal baveja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:54:04