Ryo
Ryo

Reputation: 1035

Count the keys of multi-dimension array php

Maybe the title can not explain my question ,please see my example :

I have an multi-dimension array like this :

   Array
    (
        [0] => Array
            (
                [name] => 'A'
                [ec_dest_name] => 楽天testuser_998
            ),

        [1] => Array
            (
                [name] => 'A'
                [ec_dest_name] => 楽天testuser_998
            ),
       [2] => Array
            (
                [name] => 'B'
                [ec_dest_name] => 楽天testuser_998
            ),
       [3] => Array
            (
                [name] => 'C'
                [ec_dest_name] => 楽天testuser_998
            )
)

I want to count the element by key name , it mean that I want to return an array like :

 Array ('A' => 2 , 'B'=>1, 'C'=>1)

Any quick way to accomplish that , I could loop array and count but I think it is not a good idea

Thank in advanced

Upvotes: 2

Views: 58

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

You can use array_count_values & array_column togather -

$counts = array_count_values(array_column($your_array, 'name'));

Output

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

Demo

As Mark Baker suggested for older PHP versions -

$counts = array_count_values(
     array_map(function($value) { 
         return $value['name']; 
     }, $your_array)
);

Upvotes: 2

Poiz
Poiz

Reputation: 7617

You may as well do that with 2 Loops as shown below. You might test this also HERE.

<?php

    $arrSections    = array();
    $arrCounts      = array();
    $arrMain        = array(
        array(
            'name'          => "A",
            'ec_dest_name'  => "楽天testuser_998",
        ),
        array(
            'name'          => "A",
            'ec_dest_name'  => "楽天testuser_998",
        ),
        array(
            'name'          => "B",
            'ec_dest_name'  => "楽天testuser_998",
        ),
        array(
            'name'          => "C",
            'ec_dest_name'  => "楽天testuser_998",
        ),
    );


    // BUNDLE ARRAYS WITH SIMILAR name INTO ONE GROUP
    // THUS CREATING A MULTI-DIMENSIONAL ARRAY WHOSE MAIN KEYS CORRESPOND TO
    // THE name OF THE MEMBER ARRAYS IN THE GROUP.
    foreach($arrMain as $iKey=>$subMain){
        $name   = $subMain['name'];

        if(!array_key_exists($name, $arrSections)) {
            $arrSections[$name] = array();
        }
        $arrSections[$name][] = $subMain;
    }
    // FETCH THE COUNTS OF EACH GROUP AND MAKE AN ARRAY OUT OF IT...
    foreach($arrSections as $k=>$v){
        $arrCounts[$k] = count($v);
    }
    var_dump($arrCounts);
    //OUTPUTS::
    array (size=3)
      'A' => int 2
      'B' => int 1
      'C' => int 1

Upvotes: 0

Related Questions