开发者

php array_unique with exceptions

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

Eg:

开发者_如何学Go
$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


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

$seen will now have only the unique values, plus the apple.


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


$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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜