如何基于数组字符串创建数组目录树

时间:2019-04-18 10:08:09

标签: php

在PHP中,我不知道如何创建递归函数或创建目录树数组的方法。

我目前已获得此数据(字符串数组),因此我需要进行递归以创建目录树。目的是创建一个递归,以便无论目录的深度如何,它都将能够映射数组目录树

array: [
  0 => "root"
  1 => "root/directory1"
  2 => "root/directory1/directory1-1"
  3 => "root/directory2"
  4 => "root/directory2/directory2-1"
  5 => "root/directory3"
  6 => "root/directory3/directory3-1"
  7 => "root/directory3/directory3-1/directory3-1-1"
  8 => "root/directory3/directory3-1/directory3-1-2"
  9 => "root/directory4"
]

基于该数据,我需要生成如下内容:

array: [
  0 => array: [
    "id" => 1
    "label" => "root"
    "path" => "root"
    "children" => array: [
        0 => array: [
            "id" => 1
            "label" => "directory1"
            "path" => "root/directory1"
            "children" => array: [
                0 => array: [
                    "id" => 1
                    "label" => "directory1-1"
                    "path" => "root/directory1/directory1-1"
                    "children => []
                ]
            ]
        ]
        1 => array: [
            "id" => 2
            "label" => "directory2"
            "path" => "root/directory2"
            "children" => array: [
                0 => array: [
                    "id" => 1
                    "label" => "directory2-1"
                    "path" => "root/directory1/directory2-1"
                    "children => []
                ]
            ]
        ],
        2 => array: [
            "id" => 3
            "label" => "directory3"
            "path" => "root/directory3"
            "children" => array:1 [
                0 => array: [
                    "id" => 1
                    "label" => "directory3-1"
                    "path" => "root/directory3/directory3-1"
                    "children => array: [
                        0 => array: [
                            "id" => 1
                            "label" => "directory3-1-1"
                            "path" => "root/directory3/directory3-1/directory3-1-1"
                            "children => []
                        ]
                        1 => array: [
                            "id" => 2
                            "label" => "directory3-1-2"
                            "path" => "root/directory3/directory3-1/directory3-1-2"
                            "children => []
                        ]
                ]
            ]
        ]
        3 => array: [
            "id" => 4
            "label" => "directory4"
            "path" => "root/directory4"
            "children" => array: []
        ],
    ]
]

如果有人可以帮助我,我将非常感谢。花了几个小时尝试不同的东西。非常感谢!

0 个答案:

没有答案