5

我找到了一些解决方案,但我无法决定使用哪一个。array_unique()在不区分大小写的数组上使用 php 函数的最紧凑和最有效的解决方案是什么?

例子:

$input = array('green', 'Green', 'blue', 'yellow', 'blue');
$result = array_unique($input);
print_r($result);

结果:

Array ( [0] => green [1] => Green [2] => blue [3] => yellow )

我们如何删除重复项green?至于要删除哪一个,我们假设带有大写字符的重复项是正确的。

例如保持PHP删除php

或保留PHP删除Php,因为PHP有更多的大写字符。

所以结果将是

Array ( [0] => Green [1] => blue [2] => yellow )

请注意,大写的绿色已被保留。

4

5 回答 5

14

这行得通吗?

$r = array_intersect_key($input, array_unique(array_map('strtolower', $input)));

不关心要保留的具体情况,但可以完成工作,您也可以尝试asort($input);在相交之前调用以保留大写值(IDEOne.com 上的演示)。

于 2011-06-05T02:03:24.100 回答
3

如果您可以使用 PHP 5.3.0,这里有一个函数可以满足您的需求:

<?php
function array_unique_case($array) {
    sort($array);
    $tmp = array();
    $callback = function ($a) use (&$tmp) {
        if (in_array(strtolower($a), $tmp))
            return false;
        $tmp[] = strtolower($a);
        return true;
    };
    return array_filter($array, $callback);
}

$input = array(
    'green', 'Green', 
    'php', 'Php', 'PHP', 
    'blue', 'yellow', 'blue'
);
print_r(array_unique_case($input));
?>

输出:

Array
(
    [0] => Green
    [1] => PHP
    [3] => blue
    [7] => yellow
)
于 2011-06-05T03:06:03.940 回答
1
function count_uc($str) {
  preg_match_all('/[A-Z]/', $str, $matches);
  return count($matches[0]);
}

$input = array(
    'green', 'Green', 'yelLOW', 
    'php', 'Php', 'PHP', 'gREEN', 
    'blue', 'yellow', 'bLue', 'GREen'
);

$input=array_unique($input);
$keys=array_flip($input);
array_multisort(array_map("strtolower",$input),array_map("count_uc",$input),$keys);
$keys=array_flip(array_change_key_case($keys));
$output=array_intersect_key($input,$keys);
print_r( $output );

将返回:

Array
(
    [2] => yelLOW
    [5] => PHP
    [6] => gREEN
    [9] => bLue
)
于 2011-06-05T03:52:37.323 回答
0

您应该首先将所有值设为小写,然后启动 array_unique 并完成

于 2011-06-05T01:56:14.647 回答
0

首先通过发送数据strtoupper()strtolower()使大小写一致来规范化您的数据。然后使用你的 array_unique()。

$normalized = array_map($input, 'strtolower');
$result = array_unique($normalized);
$result = array_map($result, 'ucwords');
print_r($result);
于 2011-06-05T01:56:18.643 回答