[英]Count unique values in a multi dimensional array
I have an array of data that I need to create a count for. 我有一个需要为其创建计数的数据数组。 The array gets build via a database connection. 该阵列通过数据库连接构建。
Array (
[0]=array(
[cause] => "Bob"
[cause_month] =>'7/2014'
)
[1]=array(
[cause] => "Tim"
[cause_month] =>'7/2014'
)
[2]=array(
[cause] => "Bob"
[cause_month] =>'7/2014'
)
[3]=array(
[cause] => "Bob"
[cause_month] =>'7/2014'
)
[4]=array(
[cause] => "Tim"
[cause_month] =>'8/2014'
)
[5]=array(
[cause] => "Tim"
[cause_month] =>'8/2014'
)
[6]=array(
[cause] => "Sally"
[cause_month] =>'8/2014'
)
)
To output an array that looks like this: 要输出如下所示的数组:
Array (
[7/2014] => [Bob]=>3,[Tim]=>1
[8/2014] => [Tim]=>2,[Sally]=>1
)
I have gone through several examples that give me unique causes by cause_month but have not been able to get the # of times that the cause was the same in that cause_month. 我已经查看了几个示例,这些示例按cause_month提供了独特的原因,但是无法获得该原因在那个cause_month中相同的次数。
Here is what i have taken from another post: 这是我从另一篇文章中摘录的内容:
$class_array = array();
foreach ($sb_array as $sa) {
$class_array[$sa['cause_month']][] = array('cause' => $sa['cause']);
}
This outputs: 输出:
[7/2014] => Bob , Tim
[8/2014] => Tim , Sally
Which is really close, but I still need the count of each cause for each cause_month 这真的很接近,但是我仍然需要每个cause_month的每个原因的计数
This should work for you: 这应该为您工作:
Just also use the name ( cause
) as second dimension key and initialize it with 0 if it doesn't exists. 还要使用名称( cause
)作为第二维密钥,如果不存在,则将其初始化为0。 Then just simply increment the count for each occurrence. 然后,只需简单地为每个事件增加计数。
$class_array = array();
foreach ($sb_array as $sa) {
if(!isset($class_array[$sa['cause_month']][$sa["cause"]]))
$class_array[$sa['cause_month']][$sa["cause"]] = 0;
$class_array[$sa['cause_month']][$sa["cause"]]++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.