简体   繁体   中英

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.

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)" ? 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,

$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.

In php 5.5 there are 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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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