Search code examples
phparraysmultidimensional-arraygroupingcounting

Identify rows of a 2d array as belonging to 1 of 3 groups and count the occurrences in each group


I have this array:

Array ( 
    [0] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [1] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [2] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [3] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [4] => Array ( [countThis_id] => 5 [icon] => add.gif [url] => add.php)
    [5] => Array ( [countThis_id] => 6 [icon] => add.gif [url] => add.php)
    [6] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)
    [7] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)     
)

I want to count the occurrences of countThis_id values as they relate to predefined groups.

  • if 1, then add one to the count_1 group total
  • if 2, then add one to the count_2 group total,
  • if any other value, then add one to the the_Rest group total.

My desired result:

Array ( 
    [0] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [1] => Array ( [countThis_id] => 1 [icon] => add.gif [url] => add.php)
    [2] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [3] => Array ( [countThis_id] => 2 [icon] => add.gif [url] => add.php)
    [4] => Array ( [countThis_id] => 5 [icon] => add.gif [url] => add.php)
    [5] => Array ( [countThis_id] => 6 [icon] => add.gif [url] => add.php)
    [6] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)
    [7] => Array ( [countThis_id] => 7 [icon] => add.gif [url] => add.php)   
    [8] => Array ( [count_1] => 2 [count_2] => 2 [the_Rest] => 4)   
)

Solution

  • $result = array('count_1' => 0, 'count_2'=>0, 'the_Rest'=>0);
    foreach($array as $arr){
       if($arr['countThis_id'] == 2){
         $result['count_1']++;
       }
       else if($arr['countThis_id'] == 1){
         $result['count_1']++;
       }
       else {
         $result['the_rest']++;
       }
    }
    
    array_push($array, $result);
    var_dump($array);