kanagama / laravel-collection-deduplicate
扩展 Collection 类,添加 deduplicate() 方法以排除重复项
v1.0.4
2023-05-03 12:02 UTC
Requires
- php: ^7.4 | ^8.0 | ^8.1 | ^8.2
- laravel/framework: ^8.0 | ^9.0 | ^10.0
Requires (Dev)
- orchestra/testbench: *
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.0 | ^10.0
This package is auto-updated.
Last update: 2024-09-10 11:17:08 UTC
README
功能概述
php 7.4 以上 Laravel 8.0 以上
添加 deduplicate() 方法以从 Collection 类中删除重复项。
现有方法 unique() 和 uniqueStrict()
已提供 unique() 和 uniqueStrict() 方法来排除集合中的重复项。这两个方法在处理嵌套数组或对象时,需要指定确定唯一性的键。
unique(), uniqueStrict()
示例
$collection = collect([ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ]); // 'brand' キーで重複を判断し削除する $unique = $collection->unique('brand'); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ] */
只要指定的键的值一致,即使其他键不一致,也会被删除。
如果不指定唯一性的键,而是希望删除完全一致的内容(例如数组内容、对象属性或值),那么……!!!!
尽管如此,如果没有这样的方法,我仍然创建了这样一个扩展功能,向 Collection 类添加了 deduplicate() 方法来删除这样的重复项。
deduplicate() 方法
只有当所有键或属性值都一致时,才会删除重复项。
示例
$collection = collect([ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], // 1つ目のキーと全く同じ配列を格納しまくる ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ]); $deduplicate = $collection->deduplicate(); $deduplicate->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], // 以降3件は1つめのキーと同じ値のため、重複として扱われ削除される ] */
※示例使用数组进行存储和比较,但无论存储的是对象、数字还是字符串,都没有问题。
使用方法
使用 composer 安装即可。这将向 Collection 类添加 deduplicate() 方法。
composer require kanagama/laravel-collection-deduplicate
github
https://github.com/kanagama/laravel-collection-deduplicate
packagist
https://packagist.org.cn/packages/kanagama/laravel-collection-deduplicate