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


当前回答

它可以通过函数我做了三个函数复制返回数组中重复的值。

第二个函数只返回那些在数组中不重复的值,第三个和完整的函数返回所有值,但不重复,如果任何值被重复,它将其转换为单个;

function duplicate($arr) {
    $duplicate;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] > 1) {
            $duplicate[$value] = $value;
        }
    }
    return $duplicate;
}
function single($arr) {
    $single;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] == 1) {
            $single[$value] = $value;
        }
    }
    return $single;
}
function full($arr, $arry) {
    $full = $arr + $arry;
    sort($full);
    return $full;
}

其他回答

使用array_unique()。

例子:

$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)

在这里,我创建了第二个空数组,并使用for循环与第一个数组有重复。它将运行与第一个数组的计数相同的时间。然后使用in_array与第一个数组的位置进行比较,并匹配它是否已经具有该项。如果不是,它会用array_push将该项添加到第二个数组中。

$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
    if(!in_array($a[$i], $b)){
        array_push($b, $a[$i]);
    }
}
print_r ($b);

这是一个很好的方法。可能要确保它的输出又回到一个数组。现在只显示最后一个唯一值。

试试这个:

$arrDuplicate = array ("","",1,3,"",5);

foreach (array_unique($arrDuplicate) as $v){
  if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);

有时候array_unique()不是解决方法, 如果你想获得唯一且重复的道具……

$unique=array("","A1","","A2","","A1","");
$duplicated=array();

foreach($unique as $k=>$v) {

if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
 { unset($unique[$kt]);  $duplicated[]=$v; }

}

sort($unique); // optional
sort($duplicated); // optional

结果

array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */

array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
//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 )