如何对"类型"中具有相同值的通知进行分组?和" message_id"列并且是连续的?
我"通知的结构"表是这样的:
[id |作者| datetime |类型| message_id | notification_to]
我已尝试使用GROUP BY
功能,但这会将所有记录分组,而不仅仅是那些彼此连续的记录。
现在我所拥有的只是一个简单的查询,因为GROUP BY
我没有取得任何成就:
$notifications = mysql_query("SELECT * FROM notifications WHERE notification_to = '$session_row_id' ORDER BY id DESC LIMIT 20", $connection);
并列出记录:
while($rows = mysql_fetch_array($notifications)) { ... }
这就是我现在所拥有的:
USER1 followed you
USER2 followed you
USER3 shared your message[ID:10]
USER4 followed you
USER5 shared your message[ID:20]
USER6 shared your message[ID:20]
USER7 shared your message[ID:30]
我想得到的是:
USER1 and 1 more followed you
USER3 shared your message[ID:10]
USER4 followed you
USER5 and 1 more shared your message[ID:20]
USER7 shared your message[ID:30]
与Twitter通知类似:view screenshot
答案 0 :(得分:0)
$notifications = mysql_query("SELECT * FROM notifications WHERE notification_to = '$session_row_id' ORDER BY id DESC LIMIT 20", $connection);
$last_notification = false;
$grouped_notifications = array();
while($row = mysql_fetch_array($notifications)) {
if($last_notification && $row['message_id'] == $last_notification['message_id'] && $row['type'] == $last_notification['type']){
$last_notification['plus']++;
}else{
$row['plus'] = 0;
$grouped_notifications[] = $row;
$last_notification = &$grouped_notifications[count($grouped_notifications)-1];
}
}
foreach($grouped_notifications as $notification){
echo $notification['author'];
if($notification['plus']>0){
echo ' and '.$notification['plus'].' more';
}
echo ' has '.$notification['type'];
}
我们收到所有通知,并使用PHP对它们进行分组(更容易)。我们检查我们处理的最后一个通知是否与当前通知相同,如果是,我们将一个添加到用户数量。否则,我们会创建一个新通知并将其链接到last_notification。
在那之后,我们只是回显我们的通知,检查是否有超过1个用户...我只是回显了你输入的类型,告诉我们应该使用什么变量或意味着什么。