【问题标题】:Linear representation of an array tree数组树的线性表示
【发布时间】:2013-07-25 14:21:27
【问题描述】:

我有一个 1 对 1 的线性树,其中语言 => 类型 => 产品 => 等;语言有很多类型,类型有很多产品等等。

我写了一个递归函数来返回一个数组,样式如下:

Array
(
    [0] => Array
    (
        [id] => 166
        [name] => product1
        [type] => product
        [depth] => 2
        [parent] => Array
            (
                [0] => Array
                    (
                        [id] => 165
                        [name] => default
                        [type] => type
                        [depth] => 1
                        [parent] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 1
                                        [name] => en
                                        [type] => language
                                        [depth] => 0
                                        [parent] => false

                                    )

                            )

                    )

            )

    )

)

我想要的是一种递归方法,它将遍历该树并提供一个数组,例如

[0] => array( 'id' => 1, 'name' => 'en'),
[1] => array( 'id' => 165, 'name' => 'default'),
[2] => array( 'id' => 166, 'name' => 'product1')

0,1,2 等于元素depth,这样我就可以构建数据的面包屑。

谢谢。

【问题讨论】:

    标签: php multidimensional-array recursive-datastructures


    【解决方案1】:

    这里的关键是创建一个可以递归调用的打印函数。我会建议这样的东西

    function print_recursive($array, $depth = 0) {
        //Code to print your stuff
    
        //Calls the print function on the parent if it's an array
        if(is_array($array['parent'])) {
            print_recursive($array['parent'], $depth+1);
        }
    }
    

    深度参数默认为 0,但我们在 $array['parent'] 上调用 print_recursive 时将其增加 1。这样,每次您在数组中深入时,它都会递增。

    【讨论】:

    • 谢谢,我度过了漫长的一天,递归函数突然变得难以想象。在您的帮助下,我完成了工作,并重新考虑到了我的项目的其余部分。
    猜你喜欢
    • 2018-09-08
    • 2016-05-22
    • 1970-01-01
    • 2018-08-03
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2021-12-14
    相关资源
    最近更新 更多