1

I want to remove duplicate values in an array except 1 value.

Eg:

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

How can I remove all duplicate values and keep all duplicate values that equal "apple"

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

There are about 400 values

4

3 回答 3

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

$seen 现在将只有唯一值,加上苹果。

于 2011-08-29T22:38:48.693 回答
1
$numbers = array_count_values($array);
$array = array_unique($array);
$array = array_merge($array, array_fill(1, $numbers['apple'], 'apple'));
于 2011-08-29T22:42:16.317 回答
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);
于 2011-08-29T22:41:53.540 回答