如何从PHP中删除数组中的所有重复项?

时间:2021-11-26 21:48:32

First of all, I'd like to point out to all you duplicate question hunters that this question does not fully answer my question.

首先,我想指出所有你复制的问题猎人,这个问题并没有完全回答我的问题。

Now, I've got an array. We'll say that the array is array(1, 2, 2, 3, 4, 3, 2)

现在,我有一个阵列。我们会说数组是数组(1,2,3,3,4,3,2)

I need to remove the duplicates. Not just one of the duplicates, but all, so that the result will be array(1, 4)

我需要删除重复项。不只是其中一个重复,而是全部,所以结果将是数组(1,4)

I looked at array_unique(), but that will only result in array(1, 2, 3, 4)

我查看了array_unique(),但这只会导致数组(1,2,3,4)

Any ideas?

有任何想法吗?

2 个解决方案

#1


12  

You could use the combination of array_unique, array_diff_assoc and array_diff:

您可以使用array_unique,array_diff_assoc和array_diff的组合:

array_diff($arr, array_diff_assoc($arr, array_unique($arr)))

#2


7  


function removeDuplicates($array) {
   $valueCount = array();
   foreach ($array as $value) {
      $valueCount[$value]++;
   }

   $return = array();
   foreach ($valueCount as $value => $count) {
      if ( $count == 1 ) {
         $return[] = $value;
      }
   }

   return $return;
}

#1


12  

You could use the combination of array_unique, array_diff_assoc and array_diff:

您可以使用array_unique,array_diff_assoc和array_diff的组合:

array_diff($arr, array_diff_assoc($arr, array_unique($arr)))

#2


7  


function removeDuplicates($array) {
   $valueCount = array();
   foreach ($array as $value) {
      $valueCount[$value]++;
   }

   $return = array();
   foreach ($valueCount as $value => $count) {
      if ( $count == 1 ) {
         $return[] = $value;
      }
   }

   return $return;
}