我正在尝试从完整路径字符串制作某种文件树.
这就是我使用的php类给我的:
/RootFolder/Folder1/File1.doc
/RootFolder/Folder1/SubFolder1/File1.txt
/RootFolder/Folder2/SubFolder1/File2.txt
/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc
我以为我可以做一个像这样的数组:
array
(
"RootFolder" => array
("Folder1" => array
("FILE" => "File1.doc"
"SubFolder1" => "File1.txt"
"SubFolder1" => "File2.txt"
)
"Folder2" => array
(
...
)
)
)
为了最终通过< li>获得此结果,或在< table>中:
RootFolder/
|_ Folder1/
| |_ SubFolder1/
| | |_ File1.txt
| | |_ File2.txt
| |_ File1.doc
|
|_ Folder2/
|_ SubFolder1/
|_ SubSubFolder1/
|_ File2.txt
我坚持这样做是因为我有点困惑,当然我不是开发人员.
也许还有另一种方法可以做到这一点?我认为加载页面时,我将有大约> 10000文件字符串来进行处理.
编辑:
实际上,我有一个php对象,它向我返回如下数组:
Array
(
[0] => Transmission\Model\File Object
(
[name:protected] => RootFolder/Folder1/File1.jpg
[size:protected] => 13324
[completed:protected] => 13324
[client:protected] =>
)
[1] => Transmission\Model\File Object
(
[name:protected] => RootFolder/Folder1/File2.mp3
[size:protected] => 10383488
[completed:protected] => 10383488
[client:protected] =>
)
[2] ...
)
我想要做的是用当前文件的名称,大小和状态制作某种文件树表.我基于这个http://labs.abeautifulsite.net/archived/phpFileTree/demo/demo_classic.php.
使用此对象,可以使用$var-> getName(),$var-> getsize()和$var-> isDone()来检索详细信息.
解决方法:
strtok将拯救您.
<?php
$input = [
'/RootFolder/Folder1/File1.doc',
'/RootFolder/Folder1/SubFolder1/File1.txt',
'/RootFolder/Folder1/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc',
];
function parseInput($input) {
$result = array();
foreach ($input AS $path) {
$prev = &$result;
$s = strtok($path, '/');
while (($next = strtok('/')) !== false) {
if (!isset($prev[$s])) {
$prev[$s] = array();
}
$prev = &$prev[$s];
$s = $next;
}
$prev[] = $s;
unset($prev);
}
return $result;
}
var_dump(parseInput($input));
输出:
array(1) {
["RootFolder"]=>
array(2) {
["Folder1"]=>
array(2) {
[0]=>
string(9) "File1.doc"
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File1.txt"
[1]=>
string(9) "File2.txt"
}
}
["Folder2"]=>
array(1) {
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File2.txt"
["SubSubFolder1"]=>
array(1) {
[0]=>
string(9) "File4.doc"
}
}
}
}
}
然后,您可以根据需要轻松地使用数组.