【问题标题】:Get chat data and sort by receiver and sender id获取聊天数据并按接收者和发送者 ID 排序
【发布时间】:2017-02-14 21:47:04
【问题描述】:

我有一个问题。

我有一个这样的数据库:

messages_id | int | Auto-increment
from | int
to | int
message | text

现在我无法按发件人 ID 对它们进行分组。我只想检索登录用户发送或接收的消息。这并不难。

SELECT * FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC

但是现在,它们没有分组。因为不同的人可以向该用户发送消息。我真的不知道从哪里开始。

我想要这样的东西:

array(
    [5] => array(
        [0] => "message One",
        [1] => "Message two"
    ),
    [32] => array(
        [0] => "message One",
        [1] => "Message two"
    )
);

5 和 32 是聊天对象的 ID。

希望大家帮忙:)

【问题讨论】:

  • 这意味着用户 1 一直在与用户 32 和 5 聊天...对吗?
  • @DipanwitaKundu 是的,没错

标签: php mysql sql multidimensional-array


【解决方案1】:

感谢所有回复。真的很欣赏它,但我自己已经想通了;)

现在我得到了以下信息:

$currentUserID = get_current_user_id();
$rows = $wpdb->get_results("SELECT * FROM `messages` WHERE `from` = '" . $currentUserID . "' OR `to` = '" . currentUserID . "' ORDER BY `messages_id` ASC");

$messages = [];

foreach($rows as $row) {
    if($row->from == $currentUserID) {
        $messages[$row->to][] .= $row->message;
    }
    else {
        $messages[$row->from][] .= $row->message;
    }
}
print_r($messages);

【讨论】:

    【解决方案2】:

    几年前我遇到过这样的问题。我这样做了:

    select 'In' as MessageDirection, `From` as Contact, `To` as UserId, Message 
    from Messages
    where `To` = 1
    union
    select 'Out' as MessageDirection, `To` as Contact, `From` as UserId, Message 
    from Messages
    where `From` = 1
    order by Contact
    

    【讨论】:

      【解决方案3】:

      试试这个:(假设每个字段必须有Auto-increment_fromto。对于收到的案例to 字段有值

      SELECT *, if(`Auto-increment_from` = 1 , 'From' , 'From') as meaage_type 
      FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC
      

      【讨论】:

      • 我已经更新了。请查看让我知道您的反馈。
      • 嗨迪潘维塔。感谢您的努力。但我已经用 PHP 自己想通了。再次感谢:)
      • 好的,没问题。谢谢。
      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      相关资源
      最近更新 更多