计算多维数组php的键

时间:2016-07-22 07:54:08

标签: php arrays

也许标题无法解释我的问题,请看我的例子:

我有一个像这样的多维数组:

   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
            )
)

我想按键name计算元素,这意味着我想返回一个数组:

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

任何快速实现这一目标的方法,我都可以循环数组并计算,但我认为这不是一个好主意

先谢谢

2 个答案:

答案 0 :(得分:2)

您可以使用array_count_values& array_column togather -

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

<强>输出

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

Demo

Mark Ba​​ker 建议使用较旧的 PHP 版本 -

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

答案 1 :(得分:0)

您可以使用2循环执行此操作,如下所示。您也可以对此进行测试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