繁体   English   中英

php array_unique例外

[英]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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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