28/10/2016 - PHP
Use example below to list all files and folders in a given folder. You can then use the result to create a treeview in your application. Outcome is always in alphabetical order.
cloud
candidates
one
one1.xls
one2.pdf
three
two
a
two
info.txt
info.txt
info.rtf
logo.jpg
readme.txt
clients
one
one
one1.txt
one2.png
one3.doc
one4.docx
two
two1.rtf
readme.txt
class TreeView
{
public function getTree($path)
{
$folders = [];
$files = [];
foreach (scandir($path) as $node) {
if ($this->filter($node)) {
continue;
}
if (is_dir($path.'/'.$node)) {
$folders[$node] = self::getTree($path.'/'.$node);
} else {
$files[] = $node;
}
}
return array_merge($folders, $files);
}
private function filter($filename)
{
return in_array($filename, ['.', '..', 'index.php', '.htaccess']);
}
}
$treeView = new TreeView();
$tree = $treeView->getTree('cloud');
print_r($tree);
As you can see below, we're filtering out some particular files.
Array
(
[candidates] => Array
(
[one] => Array
(
[0] => one1.xls
[1] => one2.pdf
)
[three] => Array
(
)
[two] => Array
(
[a] => Array
(
)
[two] => Array
(
[0] => info.txt
)
[0] => info.txt
)
[0] => info.rtf
[1] => logo.jpg
[2] => readme.txt
)
[clients] => Array
(
[one] => Array
(
[one] => Array
(
)
[0] => one1.txt
[1] => one2.png
[2] => one3.doc
[3] => one4.docx
)
[two] => Array
(
[0] => two1.rtf
)
[0] => readme.txt
)
)