有没有办法找出“深度"PHP 数组是什么? [英] Is there a way to find out how "deep" a PHP array is?

查看:34
本文介绍了有没有办法找出“深度"PHP 数组是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 数组可以为其元素创建数组.这些数组可以有数组等等.有没有办法找出 PHP 数组中存在的最大嵌套数?一个例子是一个函数,如果初始数组没有数组作为元素,则返回 1,如果至少有一个元素是数组,则返回 2,依此类推.

A PHP array can have arrays for its elements. And those arrays can have arrays and so on and so forth. Is there a way to find out the maximum nesting that exists in a PHP array? An example would be a function that returns 1 if the initial array does not have arrays as elements, 2 if at least one element is an array, and so on.

推荐答案

应该这样做:

<?php

function array_depth(array $array) {
    $max_depth = 1;

    foreach ($array as $value) {
        if (is_array($value)) {
            $depth = array_depth($value) + 1;

            if ($depth > $max_depth) {
                $max_depth = $depth;
            }
        }
    }

    return $max_depth;
}

?>

非常快速地测试它并且它似乎工作.

Tested it very quickly and it appears to work.

这篇关于有没有办法找出“深度"PHP 数组是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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