* shrink.php
<?php /** * $a = [1, 2, 3, 4, 5, 5, 5] * arrayshrink($a, 4, 7); // $a = [1,2,3,4,5] * remove elements from $start+1 to $end-1 */ function arrayshrink(array& $arr, int $start, int $end) { $n = count($arr); if ($start < -1 || $start >= $n) { throw new Exception("Illegal start"); } if ($end < $start || $end > $n) { throw new Exception("Illegal end"); } $delta = $end - $start - 1; $last = $n - $delta; for ($i = $start; $i < $last; $i++) { $arr[ $i ] = $arr[ $i + $delta ]; } for ($i = $last; $i < $n; $i++) { unset($arr[$i]); } } function sorted_array_unique(array &$a, callable $cmp) { for ($i = 0; $i < count($a); $i++) { for ($j = $i+1; $j < count($a); $j++) { if ($cmp($a[$j], $a[$i]) !== 0) { break; } } arrayshrink($a, $i, $j); } }
test:
$a = [1,1,1,2,3,4,4,4,4,4,5,5,5]; // arrayshrink($a, 5, 10); sorted_array_unique($a, function($a, $b) { return $a - $b; }); print_r($a);
E:\code\php>php shrink.php Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
参照 array_unique 系统函数:
http://php.net/manual/en/function.array-unique.php
Note: Note that array_unique() is not intended to work on multi dimensional arrays.
可是对于多维数组、或者数组元素为对象的情况不能处理
所以自己写一个函数能指定 比较元素大小的回调函数就可以了
这样可以用 usort 先排序
http://php.net/manual/en/function.usort.php
然后调用自己写的 sorted_array_unique 函数
完成去重
如果自己写个Set 集合来去重,需要的内存多。
每次都要 测试 in_array
http://php.net/manual/en/function.in-array.php
不知道数据量大时候是不是可行