0

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

0

1 Answer 1

2

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"]]++;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.