[英]Get folders and files recursively from a folder in alphabetical order in PHP?
I need to get all the folders and files from a folder recursively in alphabetical order (folders first, files after)我需要按字母顺序递归地从文件夹中获取所有文件夹和文件(首先是文件夹,然后是文件)
Is there an implemented PHP function which caters for this?是否有满足此要求的已实施 PHP function ?
I have this function:我有这个 function:
function dir_tree($dir) {
$path = '';
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..' && $dircont[$i] !== '.svn') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
I have sorted the array and printed it like so:我已经对数组进行了排序并像这样打印它:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
What I need is to know when a new sub directory is found, so I can add some spaces to print it in a directory like structure instead of just a list.我需要知道何时找到新的子目录,因此我可以添加一些空格以将其打印在结构之类的目录中,而不仅仅是列表。
Any help?有什么帮助吗?
Many thanks非常感谢
Look at the RecursiveDirectoryIterator
.查看
RecursiveDirectoryIterator
。
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure though if it returns the files in alphabetical order.我不确定它是否按字母顺序返回文件。
Edit:编辑:
As you say it does not, I think the only way is to sort them yourself.正如你所说的那样,我认为唯一的方法是自己对它们进行排序。
I would loop through each directory and put directories and files in a seperate arrays, and then sort them, and then recurse in the directories.我将遍历每个目录并将目录和文件放在单独的 arrays 中,然后对它们进行排序,然后在目录中递归。
I found a link which helped me a lot in what I was trying to achieve:我找到了一个链接,它对我想要实现的目标有很大帮助:
http://snippets.dzone.com/posts/show/1917 http://snippets.dzone.com/posts/show/1917
This might help someone else, it creates a list with folders first, files after.这可能对其他人有所帮助,它首先创建一个包含文件夹的列表,然后是文件。 When you click on a subfolder, it submits and another page with the folders and files in the partent folder is generated.
当您单击子文件夹时,它会提交并生成另一个页面,其中包含子文件夹中的文件夹和文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.