How to count array values ​​using key

I have an array like this, I need to count the values ​​of the array

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 instance

  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 to be 2

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

I need the quantity as above, how can I do this?

+5
source share
3 answers

Try just using array_map , count , & array_unique as

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

Use array_unique () and then count.

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

If you want to type for each key, follow these steps:

 $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 
+5
source

For this you should use array_count_values ​​(), here is 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 ) 
+2
source

Source: https://habr.com/ru/post/1235353/


All Articles