Array - Get Counts Group by Two Indexes

I have array similar to following array. But there are more than 2000 main items.


    [0] => Array
        (
            [0] => 1134
            [1] => 2014
            [2] => type1
        )

    [1] => Array
        (
            [0] => 1133
            [1] => 2014
            [2] => type1
        )

    [2] => Array
        (
            [0] => 1132
            [1] => 2014
            [2] => type2
        )

    [3] => Array
        (
            [0] => 1131
            [1] => 2014
            [2] => type2
        )

    [4] => Array
        (
            [0] => 1130
            [1] => 2013
            [2] => type1
        )

What I need

I want to get following output (all count by year with type).

Count of 1990 type1 = 3 items
Count of 1990 type2 = 65 items
Count of 1991 type1 = 5 items
Count of 1991 type2 = 12 items
............
............
............
............
Count of 2017 type1 = 5 items
Count of 2017 type2 = 10 items

Upvotes: 0

Views: 38

Answers (1)

Hamza Abdaoui
Hamza Abdaoui

Reputation: 2209

Create an other array that will store the count for each year like this one :

Array(year => Array(type1 => count, type2 =>count), ...)

Then loop your array, and count :

$tab = array( 
0 => Array
    (
        0 => 1134,
        1 => 2014,
        2 => 'type1'
    ),

1 => Array
    (
        0 => 1133,
        1 => 2014,
        2 => 'type1'
    ),

2 => Array
    (
        0=> 1132,
        1 => 2014,
        2 => 'type2'
    ),

3 => Array
    (
        0 => 1131,
        1 => 2014,
        2 => 'type2'
    ),

4 => Array
    (
        0 => 1130,
        1 => 2013,
        2 => 'type1'
    ));

$yeartab = array();

foreach($tab as $elt){
    $year = $elt[1];
    $type = $elt[2];
    if(array_key_exists($year, $yeartab)){
        if(array_key_exists($type,$yeartab[$year]))
            $yeartab[$year][$type]++;
        else
            $yeartab[$year][$type] = 1;
    } else {
        $yeartab[$year][$type] = 1;
    }
}

print_r($yeartab);

This will output :

Array ( 
 [2014] => Array ( [type1] => 2 [type2] => 2 ) 
 [2013] => Array ( [type1] => 1 ) 
) 

Upvotes: 1

Related Questions