企业🤖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(); ~~~