在 PHP 中回显多维数组

2022-08-31 00:02:08

我有一个多维数组,我试图找出如何简单地“回显”数组的元素。数组的深度未知,因此可以深度嵌套。

在下面的数组中,回显的正确顺序是:

This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment

这就是我所说的数组:

Array
(
    [0] => Array
        (
            [comment_id] => 1
            [comment_content] => This is a parent comment
            [child] => Array
                (
                    [0] => Array
                        (
                            [comment_id] => 3
                            [comment_content] => This is a child comment
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [comment_id] => 4
                                            [comment_content] => This is the 2nd child comment
                                            [child] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )

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

答案 1
<pre>
<?php print_r ($array); ?>
</pre>

答案 2

看起来您只是尝试从每个数组中写入一个重要值。尝试一个递归函数,如下所示:

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

您还可以使其更具动态性,并将 和 字符串作为参数传递到函数中(并在递归调用中继续传递它们)。'comment_content''child'