如何忽略大小写敏感度并计算数组值?

时间:2019-06-18 18:27:15

标签: php arrays

不管区分大小写,最简单的计数数组值的方法是什么?

尝试

$arr=array("A","B","b","A","b", "a", "A");
print_r(array_count_values($arr));

或:

$arr=array("AliCE","Alice","bob","AlICE","BOB", "aLIce", "alice");
print_r(array_count_values($arr));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

电流输出

Array
(
    [A] => 3
    [B] => 1
    [b] => 2
    [a] => 1
)

需求输出

Array
(
    [A] => 4
    [B] => 2
)

或者:

Array
(
    [a] => 4
    [b] => 2
)

3 个答案:

答案 0 :(得分:4)

您可以先使用strtoupper将字母映射为大写:

$arr = array("A","B","b","A","b", "a", "A");
print_r(array_count_values(array_map('strtoupper', $arr)));

输出:

(
    [A] => 4
    [B] => 3
)

答案 1 :(得分:2)

我会使用array_map,但可以选择将其连接为一个字符串,更改大小写并拆分为一个数组:

print_r(array_count_values(str_split(strtolower(implode($arr)))));

答案 2 :(得分:1)

您可以将foreacharray_key_existsstrtoupper一起使用

$arr=array("A","B","b","A","b", "a", "A");
$res = [];
foreach($arr as $k => $v){
    array_key_exists(strtoupper($v), $res) ? ($res[strtoupper($v)]++) : ($res[strtoupper($v)] = 1); 
}
print_r($res);

Working Example