[英]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这可能是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.您必须了解array_flip 的行为,否则您可能会得到意想不到的结果。 Some things to note are:
需要注意的一些事项是:
Use array_unique .使用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.只是一个想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.