简体   繁体   English

PHP - 计算多维数组中第一个元素的唯一值

[英]PHP - count unique values in first element in multidimensional array

I have this array: 我有这个数组:

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => c [1] => a [2] => d [3] => [4] => ) 

[2] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

[3] => Array ( [0] => a [1] => d [2] => c [3] =>b [4] => )

)

and would like to perform a count on unique values in the first element of each inner array. 并且想要对每个内部数组的第一个元素中的唯一值执行计数。 In the above example, one has 2 of b, 1 of c and 1 of a. 在上面的例子中,一个有b中的2个,c中的1个和a中的1个。

I have tested this: 我测试了这个:

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

but I can only check for one value at a time. 但我一次只能检查一个值。 Would like to know whether having an outer loop, "foreach(range('a','d') as $i)" ? 想知道是否有一个外循环,“foreach(范围('a','d')为$ i)”? Once the count is done, I am hoping to store the values in an array (ie. the found letter and the number of instances. 计数完成后,我希望将值存储在一个数组中(即找到的字母和实例数)。

Any suggestions in looping through unique values for the first element in the inner loop? 循环遍历内循环中第一个元素的唯一值的任何建议? Thank you once again! 再一次谢谢你!

Use array_key_exists & increment the count, 使用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. DEMO。

In php 5.5 there are array_column() + array_count_values() : 在php 5.5中有array_column() + array_count_values()

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

Example: 例:

<?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)));
?>

Results: 结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM