Php 将两个数组组合成一个新数组并在其中执行操作
我的数据库中有一个名为Php 将两个数组组合成一个新数组并在其中执行操作,php,arrays,laravel,Php,Arrays,Laravel,我的数据库中有一个名为Messages的表,其结构如下: id | sender_id | receiver_id | message | sent_at 这里,id是主键,sender\u id和receiver\u id是外键,消息是文本,发送时间是日期时间。现在,我有了一个名为messages.blade.php的文件,可以让用户接收和发送消息。但是如果我以逐行的方式显示所有消息,那么它看起来就不好了。因此,我计划创建一个flex,其中一列是Users,另一列是Messages。我计划做
Messages
的表,其结构如下:
id | sender_id | receiver_id | message | sent_at
这里,id
是主键
,sender\u id
和receiver\u id
是外键
,消息
是文本
,发送时间
是日期时间
。现在,我有了一个名为messages.blade.php
的文件,可以让用户接收和发送消息。但是如果我以逐行的方式显示所有消息,那么它看起来就不好了。因此,我计划创建一个flex
,其中一列是Users
,另一列是Messages
。我计划做的是,每当用户单击特定用户时,都需要显示用户发送或接收的消息。为此,我有以下php代码:
<?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.
?>
但我完全不知道从哪里开始。我想解决的问题是:
- 从第一个消息变量中提取所有用户id,并从中找出公共用户id
- 从第二个消息变量中提取所有用户id,并从中找出公共用户id
- 最后,结合用户id和查找唯一id的数组。 那我该怎么开始呢?我该怎么解决这个问题
希望我为您指出了正确的方向。您能添加预期的结果吗?
$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);
}