获取2D数组中某一列每个唯一值的计数

4
我需要计算我的二维数组第一列中的唯一值。
输入:
[
    ['b', 'd', 'c', 'a', ''],
    ['c', 'a', 'd', '',  ''],
    ['b', 'd', 'a', '',  ''],
    ['a', 'd', 'c', 'b', '']
]

目前,我有这段代码:

$count = 0;
foreach ($the_outer_array as $key=>$value) {
    if ($value [0] == 'c') {
        $count++;
    }
}

然而,我一次只能检查一个值。我应该像foreach(range('a','d') as $i)这样有一个外部循环吗?

完成计数后,我希望将这些值存储在数组中。

期望结果:

['b' => 2, 'c' => 1, 'a' => 1]
2个回答

4
使用array_key_exists函数并增加计数。
$newArray = array();
foreach ($the_outer_array as $key=>$value) {
    $firstValue = $value[0];
    if ($foundKey = array_key_exists($firstValue,$newArray)) {
        $newArray[$firstValue] += 1;
    }
   else{
        $newArray[$firstValue] = 1;
   }
}

DEMO.


3
在php 5.5中有 array_column()array_count_values():
print_r(array_count_values(array_column($array, 0)));

示例:

<?php
header('Content-Type: text/plain; charset=utf-8');

$array = [
    [ 'b', 'd', 'c', 'a' ],
    [ 'c', 'a', 'd', 'a' ],
    [ 'c', 'b', 'c', 'a' ]
];

print_r(array_count_values(array_column($array, 0)));
?>

结果:

Array
(
    [b] => 1
    [c] => 2
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接