简体   繁体   中英

how to count the array values with key

I have array like this i need to count by array values

Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ) [MSN] => Array ( [0] => Dozen ) [NeK] => Array ( [0] => Suhan [1] => Ebao ) [NetSE] => Array ( [0] => SuZhan [1] => Guhang ) )

For example

 Array ( [Cop] => Array ( [0] => Dozen [1] => Dozen [2] => Akls [3] => Akls ))

In the Cop key i have two different values for cop so i need cop should be 2

Cop - 2
MSn - 1
NeK - 2 
NetSE - 2

I need the count like above how can i do this ?

Use array_unique() and then count.

count(array_unique($array['Cop']));// output 2

If you want to print for every key do following:

$array = array('Cop'=>array('Dozen','Dozen','Akls','Akls'), 'MSN'=> array('Dozen'), 'NeK'=> array('Suhan','Ebao'));
foreach($array as $key => &$value) {
    $value = count(array_unique($array[$key]));
}
print_r($array);

Output:

Cop = 2
MSN = 1
NeK = 2

Try simply using array_map , count ,& array_unique like as

array_map(function($v) {
            return count(array_unique($v));
        }, $arr);

You should use array_count_values() for that, here's an example:

$data = array('cop' => array(0 => 'test', 1 => 'test', 2 => 'test2'));

foreach($data as $item){
    $result = array_count_values($item);
    print_r($result);
}

Outputs:

Array
(
    [test] => 2
    [test2] => 1
)

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