php array_unique with exceptions



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

,

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

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

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

大约有400个值

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

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

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

相关内容

  • 没有找到相关文章

最新更新