简体   繁体   English

PHP:过滤掉重复项的更好方法?

[英]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:需要注意的一些事项是:

  1. This will remove duplicate values这将删除重复值
  2. It removes NULL values它删除了 NULL 值
  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需要编写 function 来处理多维 arrays

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.只是一个想法。

Use PHP's array_unique() .使用 PHP 的array_unique()

Code:代码:

$filtered = array_unique($images);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM