View Single Post
Old 10-11-2008, 03:05 AM   #1 (permalink)
benton
The Contributor
 
Join Date: Apr 2008
Posts: 78
Thanks: 0
benton is on a distinguished road
Default Need alphabetized directory list

I am trying to read a list of directories from disk, indent them to show parent/child relationship and display in a dropdown list. Here's what I have so far:
PHP Code:
function GetStorageLocations($pathDir$store_locns, &$level)
{  
  if (
$handle opendir($pathDir))
  {
     while (
false !== ($file readdir($handle)))
     {
       if(
is_dir($pathDir.'/'.$file))
       {
         if (
$file != "." && $file != "..")
         {
            
$level++;
            
$fileShow str_pad($filestrlen($file) + (int)$level"-"STR_PAD_LEFT);
            
$store_locns[] = array('id' => $file'text' => $fileShow);
            
$store_locns GetStorageLocations($pathDir.'/'.$file$store_locns$level);
         }
       }     
     }
       
closedir($handle);
  }
  
$level--; 
  return 
$store_locns;

When I call that function and look at the results, they appear as
PHP Code:
parentA
-child 1 of parentA
--sub-directory in child 1
parentB
-child 1 in parentB
--sub-directory in child 1
---sub-directory in sub-directory of child 1 
That is how I want it to work. It gives a visual indication of the structure in the list.

The problem is with the sorting. From what I have read, readdir reads in the directories based on their datestamp but I want the order to be alphabetical. I've tried soting using this code
PHP Code:
function comparar($a$b) {
        return 
strnatcasecmp($a["id"], $b["id"]);
}
usort($store_locns"comparar"); 
That sorts them alphabettically but I lose the structure so that a child of one parent might be located under a different parent.

Is there a simpler way to do this or can anyone see a way to make it work correctly?
benton is offline  
Reply With Quote