用多维数组生成树



如何使用以下多维数组创建

子项目具有非零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'];
}

这就是你想要的吗?

function arrayStack( $array, $dash ){
   foreach($array as $value){
        if(isset($value['id'])){
            echo str_repeat("-", $dash).$value['id'].',';
        }else{
            $dash++;
            arrayStack( $value, $dash );
            $dash--;
        }
   }
} 
arrayStack( $myArray, 0 );

演示

相关内容

  • 没有找到相关文章

最新更新