ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 问题 在 laravel 中,使用 collect 处理数组是一件非常棒的事情。 废话少说!直接看代码,下面是一段简单的根据字段 id 去除重复记录的处理 ~~~ $arr = [ ['id' => 1, 'name' => 'lily'], ['id' => 2, 'name' => 'lucy'], ['id' => 1, 'name' => 'lily', 'email' => 'lily@temp.cn'], ['id' => 3, 'name' => 'hanmeimei'], ['id' => 4, 'name' => 'xiaocun'], ['id' => 5, 'name' => 'donggua'] ]; $result = collect($arr)->unique('id')->take(3)->toArray(); /* 处理的结果是 [ 0 => [ "id" => 1, "name" => "lily", ], 1 => [ "id" => 2, "name" => "lucy", ], 3 => [ "id" => 3, "name" => "hanmeimei", ], ] */ ~~~ 然而,现实开发中通常遇到的数组并不都那么友好,当数组变成这样了: ~~~ $arr = [ ['_source' => ['id' => 1, 'name' => 'lily'], '_id' => 1], ['_source' => ['id' => 2, 'name' => 'lucy'], '_id' => 2], ['_source' => ['id' => 1, 'name' => 'lily', 'email' => 'lily@temp.cn'], '_id' => '1game'], ['_source' => ['id' => 3, 'name' => 'hanmeimei'], '_id' => 3], ['_source' => ['id' => 4, 'name' => 'xiaocun'], '_id' => '4app'], ['_source' => ['id' => 5, 'name' => 'donggua'], '_id' => 'app5'] ]; ~~~ 那么,又该如何根据字段 id 去重呢? # 解决 ~~~ $result = collect($arr)->unique(function($item){ return $item['_source ']['id']; })->take(3)->toArray(); ~~~