使用php过滤掉数组中的重复值

时间:2010-08-27 11:09:41

标签: php arrays

请帮我用php.Consider

过滤掉数组中的重复值
$arr1 = array('php','jsp','asp','php','asp')

我希望只打印

array('php'=>2,
       'asp'=>2)

尝试了

print_r(array_count_values($arr1));

但是,它会计算每个元素。

2 个答案:

答案 0 :(得分:7)

好的,在评论和重读你的问题后,我明白你的意思。你仍然在array_count_values()

$arr1 = array('php','jsp','asp','php','asp');
$counts = array_count_values($arr1);

您只需删除仅显示一次的条目:

foreach ($counts as $key => $val) {
    if ($val == 1) {
        unset($counts[$key]);
    }
}

编辑:不想要循环?请改用array_filter()

// PHP 5.3+ only
$counts = array_filter($counts, function($x) { return $x > 1; });

// Older versions of PHP
$counts = array_filter($counts, create_function('$x', 'return $x > 1;'));

答案 1 :(得分:3)

如果您不想要计数,可以采用更简单的方法:

$arr1 = array('php','jsp','asp','php','asp');
$dups = array_diff_key($arr1, array_unique($arr1));