越来越多维阵列的总数数组 [英] getting a total count arrays of a multi-dimentional array

查看:132
本文介绍了越来越多维阵列的总数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果有一个简单的方法来得到一个多维数组里面嵌套数组数。下面是一个简单的例子。

I am wondering if there is a simple way to get the number of nested arrays inside a single multidimensional array. Here is a simple example.

 $a = array (
      'x' => 
      array (
        0 => 'a',
        1 => 'b',
        2 => 'c',
        'text' => 
        array (
          0 => 'foo',
          1 => 'bar',
          2 => 'tar',
        ),
        3 => 
        array (
          'color' => 
          array (
            0 => 'red',
            1 => 
            array (
              0 => 'blue',
              1 => 
              array (
                'yellow' => 
                array (
                  'name' => 'john',
                  0 => 'doe',
                  1 => 
                  array (
                    0 => 'jane',
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );

计数()只会回声 1 。我可以做一个foreach循环,最终得到了正确的价值,但我不知道,如果任何人都可以做的更好。也就是说,使用SPL /迭代器。

count() would only echo 1. I can do a foreach loop, end up getting the correct value, but I am not sure, if anyone can do better. Namely, using the SPL/Iterators.

推荐答案

我个人只是做一个递归函数,获取计数。大概是这样的:

I would personally just make a recursive function that gets a count. Probably something like:

/**
 * $n is an initial value if you wanted to add to the count.
 * Typically it would be zero. It is used in the array_reduce
 * $v is the array to count.
 */
function reduce($n, $v){
    //if the value is an array
    if(is_array($v)){
        //increment our count
        $n++;
        //recurse
        return array_reduce($v, 'reduce', $n);
    }
    //not an array, return our existing count
    return $n;
}

var_dump(reduce(0, $a));
//outputs: int(9)

有与此一个主要问题(pretty多的解决方案),这是引用。有可能陷入在一个循环,通过具有一个值,该值在较高深度引用本身阵列变为无限深

There is one major problem with this (and pretty much any solution) and that is references. It is possible to get caught in a loop that goes infinitely deep by having an array with a value that references itself at a higher depth.

例如:的http://$c$cpad.viper-7.com/Ie9oyQ

这篇关于越来越多维阵列的总数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆