wrossmann / array_uunique
此包的最新版本(1.0.0)没有可用的许可证信息。
1.0.0
2017-05-11 23:19 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-09-09 11:46:35 UTC
README
有各种解决方案来实现此功能,这是其中之一!
代码
<?php
if( ! function_exists('array_uunique') ) {
/**
* Remove duplicate elements from an array using a user-defined Reductor
* @param array $array
* @param callable $reductor Reduces a single array element to a simple type for strict equivalence checking.
*/
function array_uunique(array $array, callable $reductor) {
$seen = [];
return array_filter(
$array,
function($a)use(&$seen, $reductor){
$val = $reductor($a);
if( ! in_array($val, $seen, true) ) {
$seen[] = $val;
return true;
} else {
return false;
}
}
);
}
}
示例用法
<?php
require('vendor/autoload.php');
$arr = [
[ 'target' => 'a' ],
[ 'target' => 'b' ],
[ 'target' => 'c' ],
[ 'target' => 'd' ],
[ 'target' => 'c' ],
[ 'target' => 'e' ],
];
var_dump( array_uunique($arr, function($a){return $a['target'];}) );
输出
array(5) {
[0]=>
array(1) {
["target"]=> string(1) "a"
}
[1]=>
array(1) {
["target"]=> string(1) "b"
}
[2]=>
array(1) {
["target"]=> string(1) "c"
}
[3]=>
array(1) {
["target"]=> string(1) "d"
}
[5]=>
array(1) {
["target"]=> string(1) "e"
}
}
什么是 Reductor?
Reductor 是一个函数,可以将复杂类型(例如数组或对象)减少到简单类型(例如字符串或整数),以便进行简单、严格的比较。
如果这个函数有更适合的名字,请告诉我。
注意事项
- 过滤操作不是原地发生,因此可能需要两倍以上的内存使用。
- 在执行过程中维护一个唯一 Reductor 输出的数组,这也将影响内存使用。
- 考虑使用哈希函数来减小 Reductor 输出的大小。
- 假设复杂度:
n*log(n)
- 在 ##PHP@freenode.net 上有人说这“看起来很慢”,但没有提供很多解释,所以要注意这一点。
:I
- 这个没有使用比较器函数。
- 我希望尽可能多地依赖于 PHP 内置函数,虽然使用比较器可以使这个功能更加灵活,但我将不得不在用户空间中重新实现排序和迭代的元素,这并不理想。
为什么这不是 PHP 核心的部分?
TL;DR: "看起来像是一个拼写错误,并且需要与已实现的功能类似的工作量。"
给点时间吧。