优雅的排序方式,独特并消除数组中的重复项

优雅的排序方式,独特并消除数组中的重复项

问题描述:

Of course I can sort an array sort(), eliminate duplicates array_unique() and eliminate blanks array_filter(). I could do that in three lines, and then repeat those three lines for the ten arrays I have to process.

But I wanted it to be at least slightly elegant, so I tried to combine all three operations. It did work for the first two, then I pushed it too far and applied the sort()

$testArray = sort(array_filter(array_unique($testArray)));

This produced:

Strict Standards: Only variables should be passed by reference

So what would be the most elegant way to accomplish this array processing goal?

Bonus points for helping me understand why it failed.

当然我可以对数组 sort() code>进行排序,消除重复 array_unique () code>并消除空白 array_filter() code>。 我可以在三行中完成,然后为我必须处理的十个数组重复这三行。 p>

但我希望它至少有点优雅,所以我试着组合 em>所有三个操作。 它确实适用于前两个,然后我把它推得太远并应用了sort() p>

  $ testArray = sort(array_filter(array_unique($ testArray))); \  n  code>  pre> 
 
 

这产生了: p>

严格标准:只应通过引用传递变量 p> \ n blockquote>

那么实现这个数组处理目标最优雅的方法是什么? p>

帮助我理解它失败的原因。 p> div>

Just as a prove of concept you can kind of avoid creating in-between variables and mutating the original array. Take a look at SplMinHeap from Standard PHP Library (SPL). You can use this class for immutable sorting:

$testArray = iterator_to_array(array_reduce(
    array_filter(array_unique($testArray)),
    function ($heap, $element) {
        $heap->insert($element);
        return $heap;
    },
    new SplMinHeap
));

Here is working demo.

Your code $testArray = sort(array_filter(array_unique($testArray))); doesn't work as you expect due to a misuse of sort() function:

  1. sort() returned values are TRUE or FALSE. Not an array as you expect.
  2. sort() elements of the recived array parameter will be arranged on the array itself. So it needs an actual array to work on it; not the resturned value of other functions, which doesn't really exists as a variable. That's the reason of the error

    Only variables should be passed by reference in...

Knowing that, and having in mind that in PHP the value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3 . a first approach to fix the error might be:

sort($testArray = array_filter(array_unique($testArray)));

...but it won't work either. The assignment return the value of $testArray, not $testArray itself. Same problem as before.

At this point, the easiest way of solving so without unnecessary overhead: use two lines of code instead of one.

$testArray = array_filter(array_unique($testArray));
sort($testArray);

Test it here.