View Single Post
Old 01-27-2012, 10:36 AM   PM User | #25
Dieter Gribnitz
New to the CF scene

 
Join Date: Jan 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Dieter Gribnitz is an unknown quantity at this point
dir to array recursive

The functions on this site did not work for me.
I wrote one myself.
It converts the directory structure into an array.
It returns some relevant data in the {data} key and loops through the rest.
It might not be the cleanest script but it does the job for me.
Maybe it helps someone.

PHP Code:
  //$include overrides $exclude. $include should be an array of file extensions eg. array("jpg", "png", "gif")
  
function readDirectory($path="./"$exclude=array("."".."".htaccess"), $include=false){
    
$ds "/";
    if(!
$path){ $path=$this->path;}
    
$return = array();
    
$return['{data}']['path'] = $path;
    
$return['{data}']['has_files'] = 0;
    
$return['{data}']['has_dirs'] = 0;
    
    if(
is_dir($path)){
      
$dir opendir($path);
      while (
$file readdir($dir)) {
        
        if(
is_dir($path.$ds.$file)){
          if(
$file != "." && $file != ".."){
            
$return[$file] = array();
          }
        } else { 
          if(!
$include){
            if(!
in_array($file$exclude)){
              
$return['{data}']['files'][] = $file;
              
$return['{data}']['has_files'] = 1;
            }
          } else {
            
$ext end(explode("."$file));//GET FILE EXTENSION
            
if(in_array($ext$include)){
              
$return['{data}']['files'][] = $file;
              
$return['{data}']['has_files'] = 1;
            }
          }
        }
        
      }
    }
    if(
is_array($return)){
      
      
ksort($return);
      if(isset(
$return['{data}']['files'])){
        
natcasesort($return['{data}']['files']);//SORT CASE INSENSETIVE
        
$return['{data}']['files'] = array_values($return['{data}']['files']);//REINDEX KEYS
      
}
      foreach(
$return as $key => $value){
        if(
is_array($value)){
          if(
$key != '{data}'){
            
$return['{data}']['has_dirs'] = 1;
            
$return[$key] = readDirectory($path.$key.$ds$exclude$include);
          }
        }
      }
    }
    return 
$return;
  } 
Dieter Gribnitz is offline   Reply With Quote