不管区分大小写,最简单的计数数组值的方法是什么?
$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));
Array
(
[A] => 3
[B] => 1
[b] => 2
[a] => 1
)
Array
(
[A] => 4
[B] => 2
)
或者:
Array
(
[a] => 4
[b] => 2
)
答案 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)
您可以将foreach
与array_key_exists
和strtoupper
一起使用
$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);