我有一个数据数组,我需要为其创建计数。该数组通过数据库连接构建。
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'
)
)
输出如下所示的数组:
Array (
[7/2014] => [Bob]=>3,[Tim]=>1
[8/2014] => [Tim]=>2,[Sally]=>1
)
我已经经历了几个例子,这些例子通过cause_month给出了我独特的原因,但是却没有能够得到原因在该cause_month中相同的次数。
以下是我从另一篇文章中摘录的内容:
$class_array = array();
foreach ($sb_array as $sa) {
$class_array[$sa['cause_month']][] = array('cause' => $sa['cause']);
}
输出:
[7/2014] => Bob , Tim
[8/2014] => Tim , Sally
哪个非常接近,但我仍然需要为每个cause_month计算每个原因
答案 0 :(得分:2)
这应该适合你:
也可以使用名称(cause
)作为第二维键,如果它不存在则将其初始化为0。然后只需简单地增加每次出现的计数。
$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"]]++;
}