Gary Senter
Gary Senter

Reputation: 29

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.

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

Upvotes: 0

Views: 47

Answers (1)

Rizier123
Rizier123

Reputation: 59681

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. 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"]]++;
}

Upvotes: 2

Related Questions