在PHP中将一个文件名列表转换为文件树


Convert a list of filenames to filetree in PHP?

是否有任何库或插件,我可以使用它来轻松地将文件名列表转换为文件树?

例如,我有一个数组,其中包含我从text中读取的文件名列表:

C'Folder1'Flower.jpg
C'Folder1'Monkey.jpg
C'Folder1'Hello.jpg
C'Folder2'Binkie.txt
C'Folder2'Spike.png
C'Folder3'Django.jpg
C'Folder3'Tessje.tiff

如何在filetree中显示上面的文件名列表?我见过的大多数文件树插件要么需要一个真正的文件和文件夹结构,要么非常复杂难以理解。

如果你有这样的数组:

array(
    'c' => array(
        'Folder1' => array(
            'Flower.jpg',
            'Monkey.jpg',
            ...
        ),
        'Folder2' => array(
            'Binkie.txt',
            ...
        ),
    ),
),

可以使用递归函数:

<?php
$arr = array(
    'c' => array(
        'Folder1' => array(
            'Flower.jpg',
            'Monkey.jpg',
            //...
        ),
        'Folder2' => array(
            'Binkie.txt',
            //...
        ),
    ),
);
function drawTree($container, $nesting = 0)
{
    foreach ($container as $folder => $sub) {
        if (is_array($sub)) {
            echo str_repeat('.', $nesting) . $folder . '<br>';
            drawTree($sub, $nesting + 1);
        } else {
            echo str_repeat('.', $nesting) . $sub . '<br>';
        }
    }
}
drawTree($arr);

转换路径到数组树,使用:

$arr = array(
    'C/Folder1/Flower.jpg',
    'C/Folder1/Monkey.jpg',
    'C/Folder1/Hello.jpg',
    'C/Folder2/Binkie.txt',
    'C/Folder2/Spike.png',
    'C/Folder3/Django.jpg',
    'C/Folder3/Tessje.tiff',
);
$result = array();
foreach ($arr as $file) {
    $exp = explode('/', $file);
    $curr = &$result;
    while (true) {
        $chunk = array_shift($exp);
        if (empty($exp)) {
            $curr[] = $chunk;
            break;
        }
        if (!isset($curr[$chunk])) {
            $curr[$chunk] = array();
        }
        $curr = &$curr[$chunk];
    }
}
var_dump($result);