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()));
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.