php - 使用php计算关联数组中元素的深度

标签 php recursion associative-array

我一直在尝试编写一个递归函数来为我提供给定元素的深度,但没有成功。我似乎无法理解递归。这就是我所拥有的,但它无法正常工作:

function getDepth($a, $e, $depth = 0) {
  foreach ($a as $key => $val) {
    if (is_array($val)) {
      if ($key == $e) {
        return $depth;
      }
      return getDepth($val, $e, $depth + 1);
    }
    else {
      if ($val == $e) {
        return $depth;
      }
      else {
        return 1;
      }
    }
  }
}

任何人都可以帮助指出我在这里做错了什么吗?预先感谢您的帮助。

编辑:

@Brad @Amber @Viktor 谢谢,但这似乎也不起作用。这就是我所追求的......我有一个看起来像这样的数组:

[antonio] => Array
(
    [ian] => Array
        (
            [molly] => Array
                (
                    [blake] => blake
                )

        )

    [shonda] => Array
        (
            [dana] => dana
            [james] => james
        )

    [nels] => Array
        (
            [jason] => jason
            [danny] => danny
        )

    [molly] => Array
        (
            [blake] => blake
        )

    [blake] => blake
    [travis] => travis
)

这是一棵树,我希望找到给定名称的深度级别。所以,我需要传递一个名字,比如 blake。然后我想遍历整棵树以跟踪 blake 的深度,只要我发现他可能在树中的不同级别(并且在本例中确实如此)。假设最顶层的深度级别是 0,blake 在 antonio => ian => molly => blake 下的级别是 3,但是他在 antonio => blake 下的级别是 1,所以我想返回 1。我将不得不遍历整个树(幸运的是这个函数不会经常被调用)以确保我已经为给定用户找到了树中最浅的深度。再次感谢您的帮助。

最佳答案

基本上,要使递归正确,如果您知道您的函数中有一个数组,请在其上运行相同的函数。我们添加迄今为止最深的路径+1。最后,您会得到想要的东西。

function getDepth($a) {
    $max=0;
    foreach ($a as $val) {
        if (is_array($val)) {
            $tmp_depth=getDepth($val);
            if ($max<($tmp_depth)) {
                $max=$tmp_depth;
            }
        }
    }
    return $max+1;
}

我还没有对这个或任何东西进行基准测试。毫无疑问,速度可能会有所提高,如果这很重要的话。

关于php - 使用php计算关联数组中元素的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7718413/

相关文章:

php - 尝试读取数组上的属性 "title"(错误异常)Laravel Php

php - 使用 LIKE 和 = 的组合过滤多列

php - jQuery 函数调用 ajax 不起作用/返回任何内容

function - 在递归函数中保留变量的值,python 3.3

javascript - vuejs 2.0 中的递归组件通信

PHP - 需要帮助将数组插入给定键的关联数组

php - Eloquent 查询 AND OR

c# - 在 C# 中遍历树的递归 lambda 表达式

linux - 在 bash 关联数组中使用变量作为键

php - 在 MYSQL 中读取和写入 PHP 数组