简体   繁体   中英

php array_unique with exceptions

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM