从关联数组中删除重复的对象

时间:2019-01-16 19:20:38

标签: php laravel laravel-5 lumen

我正在为用户和顾问开发一个聊天系统,以显示一个收件箱视图,在其中我们可以看到用户的最后一条消息和个人资料图像,在打开它时,我们可以与他们进行详细的聊天, 现在要显示来自lumen API的收件箱视图,我在其中发送用户的sendBy ID,并且从该用户发送的所有消息都会得到相应的响应,现在的问题是,如果用户向同一用户两次发送消息,他的对象也在重复,但是我想要唯一sentTo键入所有json对象。 我想根据sendTo键进行区分。其余数据保持不变,但只有sendTo键是唯一的。

  public function getConversationuser(Request $request)
      {         
         $sentBy = $request->input('sentBy');

         $sentBy = DB::table('chats') 
            ->where('sentBy', '=', $sentBy)
            ->orderBy('chats.created_at','desc')  
             ->get()->toArray();

             return $sentBy;
      }  

它返回此json,我也尝试了distinct('sentTo')和groupBy('sentTo')但没有运气

 [
            {
                "id": 2,
                "sentBy": 16,
                "sentTo": 1,
                "message": "toAdvisor",
                "chatStatus": 0,
                "time": "2019-01-16 14:42:55",
                "senderType": null,
                "created_at": "2019-01-16 09:42:55",
                "updated_at": "2019-01-16 09:42:55"
            },
            {
                "id": 1,
                "sentBy": 16,
                "sentTo": 1,
                "message": "toAdvisor",
                "chatStatus": 0,
                "time": "2019-01-16 14:42:40",
                "senderType": null,
                "created_at": "2019-01-16 09:42:40",
                "updated_at": "2019-01-16 09:42:40"
            },
            {
                "id": 3,
                "sentBy": 16,
                "sentTo": 2,
                "message": "toAdvisor",
                "chatStatus": 0,
                "time": "2019-01-16 14:42:40",
                "senderType": null,
                "created_at": "2019-01-16 09:42:40",
                "updated_at": "2019-01-16 09:42:40"
            }
        ]

但是我想要

 [
        {
            "id": 2,
            "sentBy": 16,
            "sentTo": 1,
            "message": "toAdvisor",
            "chatStatus": 0,
            "time": "2019-01-16 14:42:55",
            "senderType": null,
            "created_at": "2019-01-16 09:42:55",
            "updated_at": "2019-01-16 09:42:55"
        }, 
        {
            "id": 3,
            "sentBy": 16,
            "sentTo": 2,
            "message": "toAdvisor",
            "chatStatus": 0,
            "time": "2019-01-16 14:42:40",
            "senderType": null,
            "created_at": "2019-01-16 09:42:40",
            "updated_at": "2019-01-16 09:42:40"
        }
    ]

1 个答案:

答案 0 :(得分:2)

删除toArray(),以便默认情况下雄辩地返回一个集合,然后您可以应用:

$newArray= $sentBy->unique('sentTo');