Echo a multidimensional array in PHP

2019-01-06 20:59发布

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

This is the array I was talking about:

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

9条回答
Evening l夕情丶
2楼-- · 2019-01-06 21:39

Try to use var_dump function.

查看更多
Luminary・发光体
3楼-- · 2019-01-06 21:41

There are multiple ways to do that

1) - print_r($array); or if you want nicely formatted array then

echo '<pre>'; print_r($array); echo '<pre/>';

//-------------------------------------------------

2) - use var_dump($array) to get more information of the content in the array like datatype and length. //-------------------------------------------------

3) - you can loop the array using php's foreach(); and get the desired output.

function recursiveFunction($array) {
    foreach ($array as $val) {
            echo $val['comment_content'] . "\n";
            recursiveFunction($vals['child']);
    }
}
查看更多
我只想做你的唯一
4楼-- · 2019-01-06 21:48

Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

查看更多
登录 后发表回答