开发者

PHP: Better way to filter out duplicates?

I have an array sort of like this.

$images = array
(
    array('src' => 'a.jpg'),
    array('src' => 'b.jpg'),
    array('src' => 'c.jpg'),
    array('src' => 'd.jpg'),
    array('src' => 'b.jpg'),
    array('src' => 'c.jpg'),
    array('src' => 'b.jpg'),
);

There is also height and width, but not important here. What I want is to remove the duplicates. What I have done feels rather clunky.

$filtered = array();开发者_开发问答
foreach($images as $image)
{
    $filtered[$image['src']] = $image;
}
$images = array_values($filtered);

Is there a better way to do this? Any advice?


This would probably be a good use case for array_reduce

$images = array_values(array_reduce($images, function($acc, $curr){
    $acc[$curr['src']] = $curr;
    return $acc;
}, array()));


Use array_unique.

$images = array_unique($images);


How are you building the array? Possibly keep it from ever being added using...

if(!in_array($needle, $haystackarray)){
    AddToArray;
}

Just a thought.


Sometimes I use

$filtered = array_flip(array_flip($images))

You have to understand array_flip's behavior though or you might get unexpected results. Some things to note are:

  1. This will remove duplicate values
  2. It removes NULL values
  3. It preserves keys, however, it retains the last duplicate value (not the first)
  4. A function would need to be written to handle multidimensional arrays


Use PHP's array_unique().

Code:

$filtered = array_unique($images);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜