确定PHP数组中的维数

Bri*_*ian 21 php

有没有办法确定PHP数组中有多少维度?

Ali*_*xel 20

不错的问题,这是我从PHP手册中偷走的解决方案:

function countdim($array)
{
    if (is_array(reset($array)))
    {
        $return = countdim(reset($array)) + 1;
    }

    else
    {
        $return = 1;
    }

    return $return;
}
Run Code Online (Sandbox Code Playgroud)

  • 这不完全正确.因为它只测试数组的第一个元素.因此,当您确定它是均匀分布的数组数组时,这只会给出预期的结果.你必须循环遍历所有元素才能真正了解变量深度.(或者也许是一些我不知道的spiffy遍历算法) (13认同)

gho*_*g74 5

您可以尝试以下方法:

$a["one"]["two"]["three"]="1";

function count_dimension($Array, $count = 0) {
   if(is_array($Array)) {
      return count_dimension(current($Array), ++$count);
   } else {
      return $count;
   }
}

print count_dimension($a);
Run Code Online (Sandbox Code Playgroud)