php efficiently traverse directory files and subdirectories

 
 
If there are many directories, the queue method is recommended. The recursive method will be slow. The reason for the slowness is that the recursive method is implemented by calling the function itself. When the function is called, it needs to save the address and pass parameters every time it is called.
<?php  
// recursive way  
function read_dir($dir){  
    $files=array();  
    $dir_list=scandir($dir);  
    foreach($dir_list as $file){  
        if($file!='..' && $file!='.'){  
            if(is_dir($dir.'/'.$file)){  
                $files[]=read_dir($dir.'/'.$file);  
            }else{  
                $files[]=$file;  
            }  
        }  
    }  
    return $files;  
}  
// queue method   
function read_dir_queue($dir){  
    $files=array();  
    $queue=array($dir);  
    while($data=each($queue)){  
        $path=$data['value'];  
        if(is_dir($path) && $handle=opendir($path)){  
            while($file=readdir($handle)){  
                if($file=='.'||$file=='..') continue;  
                $files[] = $real_path=$path.'/'.$file;  
                if (is_dir($real_path)) $queue[] = $real_path;  
            }  
        }  
        closedir($handle);  
    }  
     return $files;  
}  
print_r (read_dir_queue ('D: / webroot / suanfa / dir')); exit;  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772903&siteId=291194637