多维数组:如何构建递归计数()

时间:2012-03-19 05:32:56

标签: php arrays

我有一个多维数组:

membership = array(5) { 
 [0]=> array(4) { [0]=> string(21) "Group A" [1]=> string(9) "10/1/2011" [2]=> string(9) "3/31/2012" [3]=> string(8) "00004130" } 
 [1]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "4/1/2011" [2]=> string(9) "9/30/2011" [3]=> string(8) "00005005" } 
 [2]=> array(4) { [0]=> string(22) "Group A" [1]=> string(9) "10/1/2010" [2]=> string(9) "3/31/2011" [3]=> string(8) "00004130" } 
 [3]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "4/1/2010" [2]=> string(9) "9/30/2010" [3]=> string(8) "00005005" }  
 [4]=> array(4) { [0]=> string(22) "Group B" [1]=> string(8) "10/1/2010" [2]=> string(9) "3/31/2011" [3]=> string(8) "00005005" }  
}

我需要发现成员资格数组中的哪个组以及它出现的次数。

PHP的 count()没有递归功能,但如果确实如此,它的输出将是理想的(即['Group A'] => 2 ['Group B'] => 3)。

我想过使用array_diff_uassoc()但是,我只是不确定。因此,在我漫无目的地沿着错误的道路前行之前,我觉得要求一些帮助是明智的。我确信不止一种方式,但我总是在SO上找到非常有趣的编码概念。

我正在运行php 5.3.5提前感谢您的建议和帮助。

2 个答案:

答案 0 :(得分:2)

这应该用最少的代码来完成:

$memberships = array(); // Your multi-dimensional array

foreach($memberships as $membership)
{
   $count[$membership[0]]++;
}

var_dump($count)

对于BTW后期的帖子感到抱歉,我想test it并确保它能按预期运行。

输出是:

array(2) {
  ["Group A"]=>
  int(2)
  ["Group B"]=>
  int(3)
}

答案 1 :(得分:1)

鉴于你拥有的,这就是它。因为你的数组只是2D

,所以甚至不需要递归
<?php
$membership = array( 
    array("Group A","10/1/2011","3/31/2012","00004130" ),
    array("Group B","4/1/2011","9/30/2011","00005005" ), 
    array("Group A","10/1/2010","3/31/2011","00004130" ), 
    array("Group B","4/1/2010","9/30/2010","00005005" ),  
    array("Group B","10/1/2010","3/31/2011","00005005" )  
);

//initialize array for safety
$count = array();

//loop through each item
foreach($membership as $row){

    //check if group exists in count array
    $group = $row[0];
    $groupExists = array_key_exists($group,$count);

    if($groupExists){
        //if we've crossed paths before, just add 1
        $count[$group]++;
    } else {
        //otherwise, let's start with 1
        $count[$group]=1;
    }
}

var_dump($count);

//output dump should look like 
array(2) {
  ["Group A"]=> int(2)
  ["Group B"]=> int(3)
}