Creating filetree from full path in php
directory, file, php, tree, treeview
Solution
`strtok` will save you.
<?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));
Output :
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"
}
}
}
}
}
Then you can use the array as easily as you want.
Problem
I'm trying to make some kind of file tree from full path strings. 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 `<li>` or in a `<table>`: ``` RootFolder/ |_ Folder1/ | |_ SubFolder1/ | | |_ File1.txt | | |_ File2.txt | |_ File1.doc | |_ Folder2/ |_ SubFolder1/ |_ SubSubFolder1/ |_ File2.txt ``` I'm stucking on this because i'm a little confused and of course i'm not a dev.. Is there maybe another way to do this? i think i will have about >10 000 file strings to proceed when page is loaded. EDIT: In fact i have a php object that returns me arrays like this: ``` 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] ... ) ``` 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. With this object, details can be retrieved with $var->getName(), $var->getsize() and $var->isDone().