Ricalsin
Ricalsin

Reputation: 940

Multi-Dimensional Array: How to build a recursive count()

I have a multi-dimensional array:

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" }  
}

I need to discover which group is in the membership array and how many times it appears.

PHP's count() does not have recursive capability, but it's output would be ideal if it did (i.e. ['Group A'] => 2 ['Group B'] => 3 ).

I thought about using the array_diff_uassoc() but, I'm just not sure. So I thought it wise to ask for some help before I wander aimlessly down the wrong path. I am sure there is more than one way, but I always find very interesting coding concepts on SO.

I'm running php 5.3.5 Thank you in advance for your suggestions and help.

Upvotes: 1

Views: 463

Answers (2)

Jeremy Harris
Jeremy Harris

Reputation: 24549

This should do the trick with minimal code:

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

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

var_dump($count)

Sorry for the late post BTW, I wanted to test it and make sure it would work as expected.

Output is:

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

Upvotes: 2

Joseph
Joseph

Reputation: 119837

given what you have, this is it. doesn't even need to be recursive since your array is just 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)
}

Upvotes: 1

Related Questions