PHP scandir results: sort by folder to file, then alphabetically

PHP reference for scandir : default sorted order in alphabetical order in ascending order.

I am creating a file browser (on Windows), so I want the addresses to be returned sorted by folder / file, and then in alphabetical order in these subsets.

Example: right now I'm viewing and displaying

Aardvark.txt BarDir BazDir Dante.pdf FooDir 

I want too

 BarDir BazDir FooDir Aardvark.txt Dante.pdf 

Other usort and is_dir() solution (which I can figure out myself), is there a quick and efficient way to do this?

Is the ninja who wrote this comment on the right track is the best way?

+4
source share
3 answers

Does it 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 cannot glob('*.*') For files, because it selects folders called like.this .

+5
source

Try it. A simple function to sort PHP scandir results using 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; } 
+2
source

I'm late to the party, but I like to offer my solution with readdir() , not glob() . What I missed in the solution is a recursive version of your solution. But with readdir it is faster than with glob.

So with glob it will 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 it basically has the same result:

 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 finds this helpful.

0
source

All Articles