讨论板的多维数组

时间:2011-01-19 01:53:49

标签: php recursion multidimensional-array

我有一个讨论的多维数组。

我正在使用递归函数(见下文)来回显此数组的值(注释)。但是使用我的函数只会出现第一个子注释(每个数组级别)。

如何调整此函数,以便我可以在每个数组级别回显所有子注释,就像在普通的讨论板中一样?

在此示例数组中,comment_id“4”和comment_id“7”位于同一级别,但使用我当前的函数时,只能查看comment_id“4”注释。

Array
(
    [0] => Array
        (
            [comment_id] => 1
            [comment_content] => This is a comment...
            [child] => Array
                (
                    [0] => Array
                        (
                            [comment_id] => 3
                            [comment_content] => This is a reply to the comment...
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [comment_id] => 4
                                            [comment_content] => This is a reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )

                                    [1] => Array
                                        (
                                            [comment_id] => 7
                                            [comment_content] => This is a another reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )

    [1] => Array
        (
            [comment_id] => 2
            [comment_content] => This is another comment...
            [child] => Array
                (
                )

        )

    [2] => Array
        (
            [comment_id] => 6
            [comment_content] => This is another comment...
            [child] => Array
                (
                )
        )
)

我目前的功能如下:

function RecursiveWrite($array) {
    foreach ($array as $vals) {
        echo $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child']);
    }
}

1 个答案:

答案 0 :(得分:0)

也许我不明白你的问题,但功能似乎很好。

我刚刚将spacer和comment_id添加到你的函数中

function RecursiveWrite($array, $spacer='') {
    foreach ($array as $vals) {
        echo $spacer . $vals['comment_id'] . ' - ' . $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child'], $spacer . '  ');
    }
}

并输出

1 - This is a comment...
  3 - This is a reply to the comment...
    4 - This is a reply to the reply...
    7 - This is a another reply to the reply...
2 - This is another comment...
6 - This is another comment...