从php中的完整路径创建文件树
我正在尝试从完整路径字符串制作某种文件树.
I'm trying to make some kind of file tree from full path strings.
这是我使用的 php-class 给我的:
This is what the php-class I use gives me:
/RootFolder/Folder1/File1.doc
/RootFolder/Folder1/SubFolder1/File1.txt
/RootFolder/Folder2/SubFolder1/File2.txt
/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc
我想我可以制作一个像这样的数组:
I thought i can make an array like:
array
(
"RootFolder" => array
("Folder1" => array
("FILE" => "File1.doc"
"SubFolder1" => "File1.txt"
"SubFolder1" => "File2.txt"
)
"Folder2" => array
(
...
)
)
)
使用 To finally get to this result with 我坚持这个是因为我有点困惑,当然我不是开发人员.. I'm stucking on this because i'm a little confused and of course i'm not a dev.. 有没有其他方法可以做到这一点?我想我将有大约 10 000 个文件字符串在页面加载时继续. Is there maybe another way to do this? i think i will have about >10 000 file strings to proceed when page is loaded. 事实上,我有一个 php 对象,它返回这样的数组: In fact i have a php object that returns me arrays like this: 我想做的是制作某种文件树表,其中包含当前文件的名称、大小和状态.我基于这个 http://labs.abeautifulsite.net/archived/phpFileTree/demo/demo_classic.php. What i want to do is make some kind of file tree table with the name, the size and status of the curent file. I'm based on this http://labs.abeautifulsite.net/archived/phpFileTree/demo/demo_classic.php. 有了这个对象,可以通过 $var->getName()、$var->getsize() 和 $var->isDone() 来检索细节. With this object, details can be retrieved with $var->getName(), $var->getsize() and $var->isDone(). 输出: 然后您就可以随心所欲地使用该数组. Then you can use the array as easily as you want. 相关文章 或
最终得到这个结果:
<li>
or in a <table>
:RootFolder/
|_ Folder1/
| |_ SubFolder1/
| | |_ File1.txt
| | |_ File2.txt
| |_ File1.doc
|
|_ Folder2/
|_ SubFolder1/
|_ SubSubFolder1/
|_ File2.txt
Array
(
[0] => TransmissionModelFile Object
(
[name:protected] => RootFolder/Folder1/File1.jpg
[size:protected] => 13324
[completed:protected] => 13324
[client:protected] =>
)
[1] => TransmissionModelFile Object
(
[name:protected] => RootFolder/Folder1/File2.mp3
[size:protected] => 10383488
[completed:protected] => 10383488
[client:protected] =>
)
[2] ...
)
推荐答案
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"
}
}
}
}
}