Page 1 of 1

Reading directory contents into array, sorted, then display

Posted: Mon Nov 28, 2005 3:22 pm
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.

Posted: Mon Nov 28, 2005 5:42 pm
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.