php array_unique有例外

时间:2011-08-29 22:34:04

标签: php arrays array-unique

我想删除除1值以外的数组中的重复值。

例如:

$array = array ("apple", "orange", "orange", "banana", "grapes","grapes", "apple");

如何删除所有重复值并保留所有重复的值等于“apple”

 $array = array ("apple", "orange", "banana", "grapes", "apple");

大约有400个值

3 个答案:

答案 0 :(得分:2)

$seen = array()
foreach ($array as $value)
    if ($value == 'apple' || !in_array($value, $seen))
        $seen[] = $value;

$ see现在只有唯一的值,加上苹果。

答案 1 :(得分:1)

$numbers = array_count_values($array);
$array = array_unique($array);
$array = array_merge($array, array_fill(1, $numbers['apple'], 'apple'));

答案 2 :(得分:0)

$array = array ("apple", "orange", "orange", "banana", "grapes","grapes", "apple");

$counts = array_count_values($array);

$new_array = array_fill(0, $counts['apple']-2, 'apple'); // -2 to handle there already being an apple from the array_unique count below.
$new_array = array_merge(array_unique($array), $new_array);