0

例如,我有数组

Array
(
    [0] => folder1/file1.txt
    [1] => folder1/file2.txt
    [2] => file2.txt
    [3] => folder2/file1.txt
    [4] => folder1/subfolder1/file1.txt
    [5] => folder1/subfolder2/file2.txt
    [6] => file1.txt
    [7] => file3.txt
    [8] => folder1/subfolder2/file1.txt
)

我需要一个线索来确定如何根据给定的值创建“目录树”数组,它可能如下所示:

Array
(
    [folder1] => Array
        (
            [0] => file1.txt
            [1] => file2.txt
            [subfolder1] => Array
                (
                    [0] => file1.txt
                )

            [subfolder2] => Array
                (
                    [0] => file1.txt
                    [1] => file2.txt
                )

        )

    [0] => file1.txt
    [1] => file2.txt
    [2] => file3.txt
)

现在第二个数组是第一个数组的树(手动制作)。=)

而且我不知道如何自动实现这一点。

4

1 回答 1

1

简单的示例(demo),它将生成您希望的输出,但是如果您在同一目录级别(demo)中具有相同的文件夹和文件名,则会发生冲突。

$files = [
    'folder1/file1.txt',
    'folder1/file2.txt',
    'file2.txt',
    'folder2/file1.txt',
    'folder1/subfolder1/file1.txt',
    'folder1/subfolder2/file2.txt',
    'file1.txt',
    'file3.txt',
    'folder1/subfolder2/file1.txt',
];

$tree = [];
foreach ($files as $file) {
    $a = explode('/', $file);
    $array = &$tree;
    foreach (array_slice($a, 0, -1) as $folder) {
        if (!isset($array[$folder])) $array[$folder] = [];
        $array = &$array[$folder];
    }
    $array[] = end($a);
}
print_r($tree);

要克服在同一级别命名的相同文件夹和文件的问题,您可以在末尾创建带有斜线的文件夹索引,例如folder/,因此不会有任何冲突(演示)。

于 2013-10-02T17:13:13.527 回答