使用多维数组构建树

时间:2014-04-13 19:07:24

标签: php arrays recursion multidimensional-array

如何使用以下多维数组制作树?

子项目具有非零 parentID

Array
(
    [0] => Array
        (
            [id] => 6
            [title] => zzz
            [parentID] => 0
            [parentName] => 
            [section] => articles
            [sort] => 0
            [level] => 0
        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 7
                    [title] => 7
                    [parentID] => 6
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [id] => 8
                            [title] => 8
                            [parentID] => 7
                            [parentName] => 
                            [section] => articles
                            [sort] => 0
                            [level] => 0
                        )

                )

        )

    [2] => Array
        (
            [id] => 1
            [title] => تست
            [parentID] => 0
            [parentName] => 
            [section] => articles
            [sort] => 0
            [level] => 0
        )

    [3] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [title] => 4
                    [parentID] => 1
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

            [1] => Array
                (
                    [id] => 5
                    [title] => 5
                    [parentID] => 1
                    [parentName] => 
                    [section] => articles
                    [sort] => 0
                    [level] => 0
                )

        )

)

如果我想通过 id 显示项目,我需要以下结果:

6
-7
--8
1
-4
-5

我的尝试:

foreach ($array as $category)
{
    $dash = str_repeat("-", array_depth($category));
    echo $dash . $category['id'];
}

1 个答案:

答案 0 :(得分:0)

的内容
function render_node($node, $indent = '') {
    $indent .= '-';
    echo $indent . $node[0]['id'];
    for($i = 1; $i < array_length($node); $i++) {
        render_node($node[$i], "$indent-");
    }
 }

未经测试,但希望您明白这一点。可能有一个错误和一些其他奇怪的事情。