php |递归的错误

时间:2014-12-18 13:50:28

标签: php recursion

我的递归功能有问题。可能你可以帮助我。 我的功能如下:

function showTree($items, $level = 0) {

            $arr = [];

            foreach ($items as $item) {
                $arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
                if (!empty($item['children'][0])) {
                    $level++;
                    $arr[] = $this->showTree($item['children'], $level);
                }
            }

            return $arr;
}

这会产生输出:

Array
(
    [0] => Category1

    [1] => Array
        (
            [0] => ::SubCategory2

            [1] => ::SubCategory1

            [2] => Array
                (
                    [0] => ::::SubSubCategory

                )

        )

)

但我需要一些其他数据作为我的输出:

 Array
    (
        [0] => Category1
        [1] => ::SubCategory2
        [2] => ::SubCategory1
        [3] => ::::SubSubCategory

    )

我的错误在哪里?谢谢!

P&GT; S:

输入:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Category1
            [parent] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 4
                            [name] => SubCategory2
                            [parent] => 1
                            [children] => Array
                                (
                                )

                        )

                    [1] => Array
                        (
                            [id] => 2
                            [name] => SubCategory1
                            [parent] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [name] => SubSubCategory
                                            [parent] => 2
                                            [children] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

        )
)

2 个答案:

答案 0 :(得分:1)

更改此行:

$arr[] = $this->showTree($item['children'], $level);

为:

$arr = array_merge($arr, $this->showTree($item['children'], $level));

即。将子项作为新值传递到当前数组时,不要添加返回的数组,而是将其值附加到当前数组。

答案 1 :(得分:0)

试试这个:

function showTree($items, $level = 0, &$arr = array()) {

        foreach ($items as $item) {
            $arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
            if (!empty($item['children'][0])) {
                $level++;
                $this->showTree($item['children'], $level, $arr);
            }
        }

        return $arr;
}