Reading directory contents into array, sorted, then display

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Reading directory contents into array, sorted, then display

Post by jayshields »

Hi guys,

At the moment, I am reading from a directory, and printing into a HTML table as going along. I want the files/dir's to be sorted by file type by default, and then allow the user to change to a different stat to sort by, the user interaction is easy, I'll sort that.

I'm just looking into reading directory contents into arrays and sorting them.

I saw this snippet on php.net, but it looks messy and I doubt it's the most efficient way to do it. I don't have alot of experience with multi-dimensional arrays or sorting them at all so I'm hoping someone can suggest something.

Heres the code:

Code: Select all

//this is a function I wrote to sort out the contents of the directory date wise for display.

 $content_array = array();

//set current working directory
$dirname = "C:\temp";

//Load Directory Into Array
$handle=opendir($dirname);
$i=0;
while ($file = readdir($handle))
if ($file != "." && $file != "..")
{
       $content_array[$i][0] = $file;
       $content_array[$i][1] = date ("Y m d", filemtime($dirname."/".$file));
       $i++;
}
//close the directory handle
closedir($handle);

//these lines sort the contents of the directory by the date
   foreach($content_array as $res)
       $sortAux[] = $res[1];
   array_multisort($sortAux, SORT_ASC, $content_array);
Obviously adding the file type and whatever to the array on loop isn't difficult, and neither is swapping it to sort by that, I just want some suggestions on if this is the quickest method.

All I want to achieve is a sorted file display.

Thanks in advance.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Ya, it looks pretty efficient. One improvement would be to use glob() as opposed to opendir(), readdir(), and closedir(). I'd also make $content_array associative. Use 'filename' and 'filetype' (or whatever else) as keys rather than 0 and 1 - makes it more obvious.

array_multisort() is a mysterious (as far as I'm concerned) and powerful beast. IMHO its the best method of sorting a multi-dimensional array.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply