PHP scandir results: sort by folder-file, then alphabetically
PHP manual for scandir: By default, the sorted order is alphabetical in ascending order.
I'm building a file browser (in Windows), so I want the addresses to be returned sorted by folder/file, then alphabetically i开发者_运维问答n those subsets.
Example: Right now, I scan and output
Aardvark.txt
BarDir
BazDir
Dante.pdf
FooDir
and I want
BarDir
BazDir
FooDir
Aardvark.txt
Dante.pdf
Other than a usort
and is_dir()
solution (which I can figure out myself), is there a quick and efficient way to do this?
The ninja who wrote this comment is on the right track - is that the best way?
Does this give you what you want?
function readDir($path) {
// Make sure we have a trailing slash and asterix
$path = rtrim($path, '/') . '/*';
$dirs = glob($path, GLOB_ONLYDIR);
$files = glob($path);
return array_unique(array_merge($dirs, $files));
}
$path = '/path/to/dir/';
readDir($path);
Note that you can't glob('*.*')
for files because it picks up folders named like.this
.
Please try this. A simple function to sort the PHP scandir results by files and folders (directories):
function sort_dir_files($dir)
{
$sortedData = array();
foreach(scandir($dir) as $file)
{
if(is_file($dir.'/'.$file))
array_push($sortedData, $file);
else
array_unshift($sortedData, $file);
}
return $sortedData;
}
I'm late to the party but I like to offer my solution with readdir()
rather than with glob()
. What I was missing from the solution is a recursive version of your solution. But with readdir it's faster than with glob.
So with glob it would look like this:
function myglobdir($path, $level = 0) {
$dirs = glob($path.'/*', GLOB_ONLYDIR);
$files = glob($path.'/*');
$all2 = array_unique(array_merge($dirs, $files));
$filter = array($path.'/Thumbs.db');
$all = array_diff($all2,$filter);
foreach ($all as $target){
echo "$target<br />";
if(is_dir("$target")){
myglobdir($target, ($level+1));
}
}
}
And this one is with readdir but has basically the same output:
function myreaddir($target, $level = 0){
$ignore = array("cgi-bin", ".", "..", "Thumbs.db");
$dirs = array();
$files = array();
if(is_dir($target)){
if($dir = opendir($target)){
while (($file = readdir($dir)) !== false){
if(!in_array($file, $ignore)){
if(is_dir("$target/$file")){
array_push($dirs, "$target/$file");
}
else{
array_push($files, "$target/$file");
}
}
}
//Sort
sort($dirs);
sort($files);
$all = array_unique(array_merge($dirs, $files));
foreach ($all as $value){
echo "$value<br />";
if(is_dir($value)){
myreaddir($value, ($level+1));
}
}
}
closedir($dir);
}
}
I hope someone might find this useful.
精彩评论