imo, you should fetch your data ordered by created_at DESC
and then while looping through your array to compare the previous timestamp with the current (in the loop) if it's more than 1h difference it should go in another group.
I'm using Carbon
which is available in Laravel 4.2.
A basic example (I believe I've not covered all of the cases, but it's a start. Left some comments and debug messages for clearance:
$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>';