聊天/消息 PHP foreach 循环混乱
我正在尝试建立一个消息系统,其中用户的消息按时间顺序显示。我希望用户对给定消息的回复直接列在他们回复的消息下方。
基本上我认为我需要以下 5 个变量:user_id
、recipient_id
、message_id
、reply_id
和 >消息
。
有人可以为此提供一个基本的 PHP 解决方案吗?我假设只需要一些 foreach
循环和 if, else 语句,我就能想出解决方案。
到目前为止,我所得到的只是回显用户的回复,而不是他们的消息,也不嵌套在他们的消息中:
<?php foreach($messages as $message)
{
$msg_id=$message->message_id;
$rply_id=$message->reply_id;
if($msg_id=$rply_id)
{
echo $message->message;
}
}
?>
I'm trying to set up a messaging system where a user's messages are displayed in chronological order. I'd like to have the user's replies to a given message be listed directly below the message they replied to.
Basically I was thinking I need the following 5 variables: user_id
, recipient_id
, message_id
, reply_id
, and message
.
Can someone offer a basic PHP solution for this? I'd assume all it will take is some foreach
loops and if, else statements, I just can come up with solution.
Here's what I have so far which only echos the user's replies and not their messages, nor nested in within their messages:
<?php foreach($messages as $message)
{
$msg_id=$message->message_id;
$rply_id=$message->reply_id;
if($msg_id=$rply_id)
{
echo $message->message;
}
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将这样做:将从
数据库中提取的数据格式化为基本的 id 索引数组和外键索引数组
从数据库中提取所有不是回复的消息,按日期排序。
按消息 ID 索引结果数组。
从数据库中提取所有作为回复的消息,按日期排序。
循环回复,将它们放入一个新的多维数组中,按reply_id分组。
的输出格式
对非回复消息进行 Foreach 循环
显示每条消息。
拉取每条消息的id,并检查它是否是replies数组中的key。
如果它存在于回复数组中...
消息 foreach 循环结束。
Here is how I would do this:
Format the data pulled from the database into a basic id-indexed array and a foreign-key-indexed array
Pull all messages from the database that are NOT replies, order by date.
Index the resulting array by message id.
Pull all messages from the database that are replies, order by date.
Loop over the replies, putting them into a new, multidimentional array, grouped by reply_id.
Formatting of output
Foreach loop over non-reply messages:
Display each message.
Pull the id of each message and check whether it is a key in the replies array.
If it is present in the replies array...
End of message foreach loop.