递归树遍历 - 如何跟踪递归级别?

发布于 2024-12-11 20:06:05 字数 2145 浏览 0 评论 0原文

我基本上试图从表示树结构的多维数组构建 html ul/li 嵌套列表。

以下代码工作正常,但我想改进它:

我需要一种方法来跟踪递归级别,以便我可以将不同的类应用于不同的级别,向生成的输出添加缩进等。

function buildTree($tree_array, $display_field, $children_field, $class='', $id='') {

  echo "<ul>\n";

  foreach ($tree_array as $row) {

    echo "<li>\n";
    echo $row[$display_field] . "\n";

    if (isset($row[$children_field])) {

      $this->buildTree($row[$children_field]);
    }
    echo "</li>\n";
  }
  echo "</ul>\n";
} 

tree_array 如下所示:

Array
(
    [0] => Array
        (
            [category_id] => 1
            [category_name] => calculatoare
            [parent_id] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [category_id] => 4
                            [category_name] => placi de baza
                            [parent_id] => 1
                        )

                    [1] => Array
                        (
                            [category_id] => 5
                            [category_name] => carcase
                            [parent_id] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [category_id] => 6
                                            [category_name] => midi-tower
                                            [parent_id] => 5
                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [category_id] => 2
            [category_name] => electronice
            [parent_id] => 0
        )

    [2] => Array
        (
            [category_id] => 3
            [category_name] => carti
            [parent_id] => 0
        )

)

$ 已将其标记为家庭作业,因为我想以此为契机来提高我对递归的(较差)理解,因此,我希望得到能够指导我找到解决方案的答案,而不是提供完整的工作示例:)

I'm basically trying to build an html ul/li nested list from a multidimensional array representing a tree structure.

The following code works fine but I want to improve it:

I need a way to keep track of the recursion level so I can apply different classes to different levels, add indenting to the generated output, etc.

function buildTree($tree_array, $display_field, $children_field, $class='', $id='') {

  echo "<ul>\n";

  foreach ($tree_array as $row) {

    echo "<li>\n";
    echo $row[$display_field] . "\n";

    if (isset($row[$children_field])) {

      $this->buildTree($row[$children_field]);
    }
    echo "</li>\n";
  }
  echo "</ul>\n";
} 

The $tree_array looks like this:

Array
(
    [0] => Array
        (
            [category_id] => 1
            [category_name] => calculatoare
            [parent_id] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [category_id] => 4
                            [category_name] => placi de baza
                            [parent_id] => 1
                        )

                    [1] => Array
                        (
                            [category_id] => 5
                            [category_name] => carcase
                            [parent_id] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [category_id] => 6
                                            [category_name] => midi-tower
                                            [parent_id] => 5
                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [category_id] => 2
            [category_name] => electronice
            [parent_id] => 0
        )

    [2] => Array
        (
            [category_id] => 3
            [category_name] => carti
            [parent_id] => 0
        )

)

I've tagged this as homework because I'd like to use this as an opportunity to improve on my (poor) understanding of recursion so, I'd appreciate answers that would guide me to the solution rather than provide a complete working example :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

誰ツ都不明白 2024-12-18 20:06:05

快速而肮脏的方法(请参阅下面的“剧透”块以了解实现):

在函数声明中添加一个附加变量 $recursionDepth ,默认情况下将其设置为 0

在每个后续递归中,使用 $recursionDepth + 1 调用您的函数。

由于函数变量仅对于函数的相应实例“可见”(作用域),因此您最终将得到当前迭代深度的指示器。

另外,在我看来,函数的第 12 行

$this->buildTree();

不起作用——原因是您没有将变量传递给 buildTree 的下一个实例。

它可能应该如下所示:

$this->buildTree($row[$children_field], $display_field, $children_field, $class, $id)

这是我对您的代码进行的更改以实现您想要的效果:

function buildTree($tree_array, $display_field, $children_field, $class='', $id='', $recursionDepth = 0, $maxDepth = false)
{
    if ($maxDepth && ($recursionDepth == $maxDepth)) return;

    echo "<ul>\n";

    foreach ($tree_array as $row)
    {
        echo "<li>\n";
        echo $row[$display_field] . "\n";

        if (isset($row[$children_field]))
            $this->buildTree($row[$children_field], $display_field, $children_field, $class, $id, $recursionDepth + 1, $maxDepth);

        echo "</li>\n";
    }
    echo "</ul>\n";
}

Quick'n'dirty approach (see "spoiler" block below for the implementation):

Add an additional variable $recursionDepth to your function declaration, make it 0 by default.

On each subsequent recursion, call your function with $recursionDepth + 1.

Since the function variables are only "visible" (scoped) for the respective instance of the function, you'll end up with an indicator of the current iteration depth.

Also, line 12 of your function

$this->buildTree();

doesn't look to me as if it would work – the reason being that you're not passing your variables on to the next instance of buildTree.

It probably should look like this:

$this->buildTree($row[$children_field], $display_field, $children_field, $class, $id)

Here's the changes I'd make to your code to achieve what you want:

function buildTree($tree_array, $display_field, $children_field, $class='', $id='', $recursionDepth = 0, $maxDepth = false)
{
    if ($maxDepth && ($recursionDepth == $maxDepth)) return;

    echo "<ul>\n";

    foreach ($tree_array as $row)
    {
        echo "<li>\n";
        echo $row[$display_field] . "\n";

        if (isset($row[$children_field]))
            $this->buildTree($row[$children_field], $display_field, $children_field, $class, $id, $recursionDepth + 1, $maxDepth);

        echo "</li>\n";
    }
    echo "</ul>\n";
}
幽蝶幻影 2024-12-18 20:06:05

你正在让你的生活变得比需要的更加困难。 SPL 提供了许多迭代器 为了您的方便。使用 RecursiveArrayIterator 类可以轻松遍历多维数组。它不仅允许您处理任何级别深度数组,而且还可以跟踪深度。

示例

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array)
);

for($iterator; $iterator->valid(); $iterator->next())
{
    printf(
        "Key: %s Value: %s Depth: %s\n",
        $iterator->key(),
        $iterator->current(),
        $iterator->getDepth()
    );
}

键盘上的示例

如您所见,有一个方法getDepth() 它将始终告诉您当前的迭代深度。这是 RecursiveIteratorIterator 所需的方法在递归迭代器中迭代子级。

如果您需要影响迭代开始或访问子级时发生的情况,请查看我对 多维数组迭代,它显示了一个自定义的RecursiveIteratorIterator,它将把多维数组的值包装到xml元素中,并按深度缩进它们当前迭代(适应 ul/li 元素应该很简单)。

另请参阅有关迭代器的维基百科文章以获取一般介绍。

You are making your life more difficult than it needs to be. The SPL offers a number of iterators for your convenience. Traversing multidimensional arrays is easy with the RecursiveArrayIterator class. Not only does it allow you to process any level depth arrays but it also will keep track of the depth.

Example

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array)
);

for($iterator; $iterator->valid(); $iterator->next())
{
    printf(
        "Key: %s Value: %s Depth: %s\n",
        $iterator->key(),
        $iterator->current(),
        $iterator->getDepth()
    );
}

Example on codepad

As you can see, there is a method getDepth() which will always tell you the current iteration depth. It's a method of the RecursiveIteratorIterator required to iterate over the children in recursive iterators.

If you need to influence what happens when iteration starts or when children are accessed, have a look at my answer to Multidimensional array iteration which shows a custom RecursiveIteratorIterator that will wrap the values of a multidimensional array into xml elements and indent them by the depth of the current iteration (which should be trivial to adapt to ul/li elements).

Also have a look at the Wikipedia Article about Iterators for a general introduction.

情绪失控 2024-12-18 20:06:05
public virtual int GetLevelById(int id)
        {
            int i = GetParentById(id);
            if (i == 0)
                return 1;
            else
                return (1 + GetLevelById(i));
        }

公共虚拟int GetParentById(int t)
{
var ret = this._list.FirstOrDefault((f) => f.Id == t);
if (ret != null)
返回 ret.ParentId;
返回-1;
}

public virtual int GetLevelById(int id)
        {
            int i = GetParentById(id);
            if (i == 0)
                return 1;
            else
                return (1 + GetLevelById(i));
        }

public virtual int GetParentById(int t)
{
var ret = this._list.FirstOrDefault((f) => f.Id == t);
if (ret != null)
return ret.ParentId;
return -1;
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文