简体   繁体   中英

Combine two arrays to form a new one and perform operations in it

I have a table in my database named Messages and its structure is as follow:

id | sender_id | receiver_id | message | sent_at

Here, id is the primary key , sender_id and receiver_id are the foreign keys , message is text and sent_at is datetime . Now, I have a file named messages.blade.php where I will enable the users to receive and send messages. But if I show all the messages in line-by-line manner, then it wouldn't look good. So, I have planned to create a flex where one column will be Users and the another will be Messages . What I plan to do is, whenever the user clicks on a particular user, the messages sent or received by the user needs to be shown. For that I have the following php code:

    <?php
use Illuminate\Support\Facades\DB;
$my_id = \Session::get('user_id');
$messagesSentByMe = DB::table('messages')->where('sender_id', '=', $my_id)->get();
$messagesReceivedByMe = DB::table('messages')->where('receiver_id', '=', $my_id)->get();

//And the thing I wanna do is: extract similar id from the first messages, then the second messages and then from both the messages so that, I can have the user_id whom I have sent or received messages with.
?>

But I am completely blank where to start this stuff. The things that I want to tackle is:

  • Extract all the user_id from the first message variable and find out the common user_id from it
  • Extract all the user_id from the second message variable and find out the common user_id from it
  • Finally combine both the user_id and find array of the unique id only. So how am I supposed to start? What do I do to solve this problem?

You should initialise two new arrays ($sent and $received) which are indexed by sender_id and receiver_id respectively. You can then loop over your $messagesSentByMe and $messagesReceivedByMe arrays and add the messages to these arrays. eg

$sent = [];
$received = [];

foreach($messagesSentByMe as $message) {
    $receiver = $message['receiver_id'];

    // Initialize new array containing messages sent to a user
    if (!array_key_exists($receiver, $sent)) {
        $sent[$receiver] = [];
    }

    // Add message sent to user to the array
    array_push($sent[$receiver], $message);    
}

This code will group $messagesSentByMe by the user each message was sent to, you can do the same for $messagesReceivedByMe.

I'm not 100% sure what you meant by your final point, but I assume you aim to list individual conversations between the user and others. You will be able to acheive this by using the array_merge and sort functions (probably sorting by 'sent_at') see, http://php.net/manual/en/book.array.php

Hopefully I've pointed you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM