是否有可用于轻松将文件名列表转换为文件树的库或插件?
比方说,我有一个数组,其中包含我从文本中读取的文件名列表:
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中显示上面的文件名列表?我见过的大多数filetree插件都需要真正的文件和文件夹结构,或者要理解起来非常复杂。
答案 0 :(得分:1)
如果您有这样的数组:
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);
将pathes转换为数组树,请使用:
$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);