Jump to content

All files from a folder (and subfolders) into an array


majik92

Recommended Posts

Hello :)

 

I can get all the files from a folder into an array, but how do get the files from subfolders within that folder into the array too.

 

For example there are these 3 files:

original/file1.rar

original/file2.rar

original/bob/file3.rar

 

I am trying to get the above in to one array so that:

$array[0] is "original/file1.rar"

$array[1] is "original/file2.rar" and

$array[2] is "original/bob/file3.rar"

 

Thanks

http://www.phpfreaks.com/forums/index.php/topic,243563.msg1137390.html#msg1137390 Post Deleted, double post

$array = array();
if (is_dir('original')) {
    if ($dir = opendir('original')) {
        while (($file = readdir($dir)) !== false) {
            if (is_file('original/' . $file))
                $array[] = 'original/' . $file;
            elseif(is_dir('original/' . $file)) {
                if ($dir = opendir('original')) {
                    while (($file2 = readdir($dir)) !== false) {
                    if (is_file('original/' . $file . '/' . $file2))
                        $array[] = 'original/' . $file . '/' . $file2;
                }
                closedir($dir);
                }
            }
        }
        closedir($dir);
    }
}

function recdir($base) {
  $files=array();
  if(is_dir($base) &&$ $dh=opendir($base))   {
    while($file=readdir($dh))     {
       if($file=='.' || $file== '..') continue;
       if(is_dir($file)) {
         $subfiles=recdir($base.'/'.$file);
         $tfiles=array_merge($files,$subfiles);
         $files=$tfiles;
       } else {
         $files[]=$base.'/'.$file;
       }
    }
  }
  return $files;
}

 

I think that shud work :) May require tweaking, not tested

                       

   

 

laffin beats me in it :) almost same code...i just put more time to test it and it works :)

 

This code works till 3 levels of sub dirs, pl feel free to modify it as per convinience.

 

<?php 
$path = "/tmp";

function getFileList($path, $level=1) {
    $arrFiles = scandir($path);
    $arrFileList = array();
    $intCount = count($arrFiles);
    for($i=0;$i<$intCount;$i++) {
        if($arrFiles[$i] != "." && $arrFiles[$i] != "..") {
            if(is_dir($path."/".$arrFiles[$i])) {
                if($level > 3) return $arrFileList;
                $arrFileList = array_merge($arrFileList, getFileList($path."/".$arrFiles[$i],$level+1));
            } else {
                $arrFileList[] = $path."/".$arrFiles[$i];
            }
        }
    }
    return($arrFileList);
}

var_dump(getFileList($path));

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.