简单数组到关联数组,基于'目录树',就像第一个数组的值一样

时间:2013-10-02 16:31:18

标签: php arrays associative-array

例如,我有数组

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
)

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

我无法想象如何自动实现这一目标。

1 个答案:

答案 0 :(得分: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/,因此不会发生任何冲突(demo)。