如何从PHP数组中删除重复值?
当前回答
//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 )
其他回答
试试这个简短而甜蜜的代码-
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
输出-
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
这是一个很好的方法。可能要确保它的输出又回到一个数组。现在只显示最后一个唯一值。
试试这个:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
根据数组的大小,我发现
$array = array_values( array_flip( array_flip( $array ) ) );
可以比array_unique快。
在这里,我创建了第二个空数组,并使用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);