简体   繁体   中英

Recursively listing all files in directory

I have the following function:

function listFiles($dir, $results = array()){       
    $entities = is_dir($dir) ? array_values(array_diff(scandir($dir), array('..', '.'))) : false ;  
    if( $entities )
        foreach( $entities as $e ) {
            $path = $dir.'/'.$e;
            if( is_dir($path) ) {
                listFiles($path, $results);
            }   
            $results[] = $path;
        }
        return $results;
    }
print_r(listFiles('/home/apps/public_html/test_folder'));

Although this works somehow the array has only the first branch of the directory. But if I echo the path inside foreach I get the path of every file from all folders and subfolders and so on.

Probably this is something very small but I can't figure out what and I could use some help. Thank you.

inside your recursive function if a subdir is found you call the function itself with the subdir but it's results are not handled, not assigned to any variable so they are lost, you should push it to your results like this:

if( is_dir($path) ){
    $results[] = listFiles($path, $results);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM