doutang3815 2014-08-22 03:47
浏览 63
已采纳

计算某个键名出现在多个数组中的次数?

How may I count the times a key shows up in a multi-array?

In the below example, weight should return 2, and reps 4. Does PHP have a built-in function for this?

                [0] => Array
                    (
                        [0] => Array
                            (
                                [weight] => 317.51474856007
                                [reps] => 10
                            )

                        [1] => Array
                            (
                                [weight] => 50
                                [reps] => 10
                            )

                        [2] => Array
                            (
                                [reps] => 10
                            )

                        [3] => Array
                            (
                                [reps] => 10
                            )

                    )
  • 写回答

3条回答 默认 最新

  • dongzizhi9903 2014-08-22 04:11
    关注

    Try this one liner using array_walk_recursive():

    Given your array, $arr

    array_walk_recursive($arr, function($v, $k)use(&$count){if(array_key_exists($k, $count))$count[$k]++;else $count[$k]=1;},$count=array());
    print_r($count);
    

    See demo

    or the old fashioned way:

    $count = array();
    foreach ($arr as $ar){
        foreach ($ar as $k=>$v){
            if (array_key_exists($k, $count)){
                $count[$k]++;
            }
            else{
                $count[$k] = 1;
            }
        }
    }
    print_r($count);
    

    See demo

    Output:

    Array
    (
        [weight] => 2
        [reps] => 4
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改