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:
- This will remove duplicate values
- It removes NULL values
- It preserves keys, however, it retains the last duplicate value (not the first)
- A function would need to be written to handle multidimensional arrays
Use PHP's array_unique()
.
Code:
$filtered = array_unique($images);
精彩评论