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
Cop - 2
MSn - 1
NeK - 2
NetSE - 2
I need the count like above how can i do this ?
我需要像上面这样的计数我该怎么做?
3 个解决方案
#1
5
Try simply using array_map
,count
,& array_unique
like as
尝试简单地使用array_map,count和array_unique
array_map(function($v) {
return count(array_unique($v));
}, $arr);
#2
5
Use array_unique() and then count.
使用array_unique()然后计数。
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
#3
2
You should use array_count_values() for that, here's an example:
你应该使用array_count_values(),这是一个例子:
$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
)
#1
5
Try simply using array_map
,count
,& array_unique
like as
尝试简单地使用array_map,count和array_unique
array_map(function($v) {
return count(array_unique($v));
}, $arr);
#2
5
Use array_unique() and then count.
使用array_unique()然后计数。
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
#3
2
You should use array_count_values() for that, here's an example:
你应该使用array_count_values(),这是一个例子:
$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
)