
本文档旨在指导开发者如何使用 PHP 处理从数据库获取的 JSON 数组数据,并为每个 JSON 对象添加基于时间戳计算出的“时间前”信息。通过示例代码,详细讲解如何遍历数组、计算时间差,并将计算结果合并到原始 JSON 数据中,最终生成包含时间信息的 JSON 数组。
核心在于使用 foreach 循环遍历 JSON 数组,并在循环内部计算时间差,然后将计算得到的时间信息添加到原始数组的每个元素中。
[
{"id": "475", "CreatedAt": "1636953999"},
{"id": "474", "CreatedAt": "1636953988"},
{"id": "473", "CreatedAt": "1636953977"}
]这段数据存储在 PHP 变量 $CommentTime 中,它是一个数组,每个元素都是一个关联数组。
<?php
$CommentTime = [
["id" => "475", "CreatedAt" => "1636953999"],
["id" => "474", "CreatedAt" => "1636953988"],
["id" => "473", "CreatedAt" => "1636953977"]
];
foreach ($CommentTime as &$cmt) {
$CreatedAt = $cmt['CreatedAt'];
$PostedAts = $CreatedAt;
$time_ago = $PostedAts;
$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);
// Seconds
if ($seconds <= 60) {
$PostedTime = "just now";
} //Minutes
else if ($minutes <= 60) {
if ($minutes == 1) {
$PostedTime = "one minute ago";
} else {
$PostedTime = "$minutes minutes ago";
}
} //Hours
else if ($hours <= 24) {
if ($hours == 1) {
$PostedTime = "an hour ago";
} else {
$PostedTime = "$hours hrs ago";
}
} else if ($days <= 7) {
if ($days == 1) {
$PostedTime = "yesterday";
} else {
$PostedTime = "$days days ago";
}
} else if ($weeks <= 4.3) { // Roughly a month
if ($weeks == 1) {
$PostedTime = "a week ago";
} else {
$PostedTime = "$weeks weeks ago";
}
} else if ($months <= 12) {
if ($months == 1) {
$PostedTime = "a month ago";
} else {
$PostedTime = "$months months ago";
}
} else {
if ($years == 1) {
$PostedTime = "one year ago";
} else {
$PostedTime = "$years years ago";
}
}
$cmt['Time'] = $PostedTime;
}
echo json_encode($CommentTime);
?>将时间信息添加到数组元素: 在循环内部,将计算得到的 $PostedTime 赋值给 $cmt['Time']。 由于使用了引用传递,这一操作会直接修改 $CommentTime 数组中的元素。
立即学习“PHP免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
输出 JSON 数据: 循环结束后,使用 json_encode() 函数将 $CommentTime 数组转换为 JSON 格式并输出。
最终的输出结果如下:
[
{"id": "475", "CreatedAt": "1636953999", "Time": "2 hrs ago"},
{"id": "474", "CreatedAt": "1636953988", "Time": "2 hrs ago"},
{"id": "473", "CreatedAt": "1636953977", "Time": "2 hrs ago"}
]注意: 由于 time() 函数返回的是当前服务器的时间戳,实际运行结果会根据当前时间与 CreatedAt 的时间差而变化。 示例代码中使用了固定的 $CommentTime 数据,实际应用中需要替换为从数据库获取的数据。
通过使用 foreach 循环和引用传递,可以方便地修改 JSON 数组中的元素,并添加基于时间戳计算得到的时间信息。 这种方法简单高效,适用于处理需要添加时间信息的 JSON 数据。 同时,请注意时间差计算的准确性和时区问题,确保显示的时间信息符合预期。
以上就是PHP JSON 数组合并:添加时间戳信息的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号