我想删除除1值以外的数组中的重复值。
例如:
$array = array ("apple", "orange", "orange", "banana", "grapes","grapes", "apple");
如何删除所有重复值并保留所有重复的值等于“apple”
$array = array ("apple", "orange", "banana", "grapes", "apple");
大约有400个值
答案 0 :(得分:2)
$seen = array()
foreach ($array as $value)
if ($value == 'apple' || !in_array($value, $seen))
$seen[] = $value;
$ see现在只有唯一的值,加上苹果。
答案 1 :(得分:1)
$numbers = array_count_values($array);
$array = array_unique($array);
$array = array_merge($array, array_fill(1, $numbers['apple'], 'apple'));
答案 2 :(得分: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);