按时间分组并显示它们

用户名

我有一个任务来创建活动供稿视图,例如https://dribbble.com/shots/1434168-Assembly-Activity-Stream/attachments/211032

我想将注释/帖子分组为“一个小时前”,“ 2小时前”,“ 3 ..”等组,并将其显示在页面上。(如图所示)例如,我的数组如下所示:

$data = array(
    array(
            'id' => 1,
            'msg' => '...',
            'created_at' => timestamp
        ),
    array(
            'id' => 2,
            'msg' => '...',
            'created_at' => timestamp
        ),
    ...
    ...
);

最好的解决方案是什么?

伊万卡·托多罗娃(Ivanka Todorova)

imo,您应该按以下顺序获取数据created_at DESC,然后在遍历数组时将前一个时间戳与当前(在循环中)进行比较(如果相差超过1小时),则该时间戳应进入另一组。

我正在使用CarbonLaravel 4.2中可用的版本。

一个基本示例(我相信我并未涵盖所有情况,但这只是一个开始。留下一些注释和调试消息以供清除:

$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>';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章