在 PHP 中回显多维数组 [英] Echo a multidimensional array in PHP

查看:29
本文介绍了在 PHP 中回显多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,我正在尝试找出如何简单地回显"数组的元素.数组的深度未知,因此可以深度嵌套.

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.

对于下面的数组,正确的回显顺序是:

In the case of the array below, the right order to echo would be:

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
                (
                )
        )
)

推荐答案

看起来您只是想从每个数组中写入一个重要值.试试这样的递归函数:

It looks like you're only trying to write one important value from each array. Try a recursive function like so:

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

你也可以让它更动态一点,将 'comment_content''child' 字符串作为参数传递到函数中(并继续将它们传递到递归调用).

You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).

这篇关于在 PHP 中回显多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆