我有一项任务是创建活动供稿视图,例如https://dribbble.com/shots/1434168-Assembly-Activity-Stream/attachments/211032。
我想将小组中的笔记/帖子分组,例如“小时前”,“小时前”,“小时”,“等等”和“等等”。在页面上显示它。 (就像在图像中一样)例如我的数组看起来像:
$data = array(
array(
'id' => 1,
'msg' => '...',
'created_at' => timestamp
),
array(
'id' => 2,
'msg' => '...',
'created_at' => timestamp
),
...
...
);
这样做的最佳解决方案是什么?
答案 0 :(得分:2)
您可以创建一个功能:
function dateDifference($first,$last){
$hourdiff = round((strtotime($last) - strtotime($first))/3600);
return $hourdiff;
}
$dt1= "2015-06-05 11:07:23";
$dt2= date("Y-m-d H:i:s");
echo dateDifference($dt1,$dt2);
答案 1 :(得分:2)
答案 2 :(得分:1)
imo,您应该获取created_at DESC
所订购的数据,然后在循环浏览数组时将之前的时间戳与当前(在循环中)进行比较,如果超过1小时的差异,它应该去在另一组。
我正在使用Laravel 4.2中提供的Carbon
。
一个基本的例子(我相信我并未涵盖所有案例,但它是一个开始。留下一些评论和调试消息以便清除:
$activityPosts = [
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 20:00'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 19:37'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 19:29'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 19:13'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 18:25'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 18:01'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 13:56'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 12:18'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 12:05'),
],
[
'id' => null,
'msg' => 'Message #',
'created_at' => strtotime('yesterday 10:28'),
]
];
$activityPosts = array_reverse($activityPosts); //I just built the array wrong (Im not a smart girl...)
echo '<div style="border: 1px solid red; width: 250px; margin-bottom: 5px">';
foreach ($activityPosts as $k => $post) {
$getHour = \Carbon\Carbon::createFromTimeStamp($post['created_at'])->hour;
if (isset($activityPosts[$k - 1])) {
$prevHour = \Carbon\Carbon::createFromTimeStamp($activityPosts[$k - 1]['created_at'])->hour;
if ($getHour !== $prevHour) {
echo '</div>';
echo '<div style="border: 1px solid red; width: 250px;margin-bottom: 5px">';
}
echo '<hr />';
echo 'Current: ' . $getHour . 'h Prev:' . $prevHour . 'h';
echo '<hr />';
}
echo "<h4>Message: {$post['msg']}{$k}</h4>";
echo $post['created_at'];
echo '<h4>' . \Carbon\Carbon::createFromTimeStamp($post['created_at'])->diffForHumans() . '</h4>';
}
echo '</div>';