数组树的线性表示

时间:2013-07-25 14:21:28

标签: php multidimensional-array recursive-datastructures

我有1到1个线性树,其中languages => types => products =>等等;语言有很多种类和类型,有很多产品等等。

我编写了一个递归函数来返回以下样式的数组:

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,那么我可以构建数据的面包屑。

谢谢。

1 个答案:

答案 0 :(得分: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);
    }
}

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

相关问题