如何从PHP数组中删除重复值?


当前回答

根据数组的大小,我发现

$array = array_values( array_flip( array_flip( $array ) ) );

可以比array_unique快。

其他回答

$result = array();
foreach ($array as $key => $value){
  if(!in_array($value, $result))
    $result[$key]=$value;
}

有多种方法可以做到这一点,如下所示

//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));

//second method
$array = array_unique($arr, SORT_REGULAR);

我没有使用任何函数。

$arr = array("1", "2", "3", "4", "5", "4", "2", "1");

$len = count($arr);
for ($i = 0; $i < $len; $i++) {
  $temp = $arr[$i];
  $j = $i;
  for ($k = 0; $k < $len; $k++) {
    if ($k != $j) {
      if ($temp == $arr[$k]) {
        echo $temp."<br>";
        $arr[$k]=" ";
      }
    }
  }
}

for ($i = 0; $i < $len; $i++) {
  echo $arr[$i] . " <br><br>";
}
    if (@!in_array($classified->category,$arr)){        
                                    $arr[] = $classified->category;
                                 ?>

            <?php } endwhile; wp_reset_query(); ?>

第一次检查数组中的值,发现相同的值忽略它

//Find duplicates 

$arr = array( 
    'unique', 
    'duplicate', 
    'distinct', 
    'justone', 
    'three3', 
    'duplicate', 
    'three3', 
    'three3', 
    'onlyone' 
);

$unique = array_unique($arr); 
$dupes = array_diff_key( $arr, $unique ); 
    // array( 5=>'duplicate', 6=>'three3' 7=>'three3' )

// count duplicates

array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )