Page 1 of 1
directories into an array
Posted: Thu Jan 05, 2006 4:31 pm
by Extremest
I am trying to figure out how I can have php look at a certain dir and then make an array of every filename in that directory then go into the subfolders getting those names with dir also. That way afterwards it could then parse every file in all the directories.
Posted: Thu Jan 05, 2006 4:56 pm
by feyd
a lot of people write recursive loops to generate such things using
glob() or
opendir()/
readdir(). I use a different approach, because I have a general hate for recursive functions (old stack space issue). My approach uses two loops, and two arrays. The first array is for directories, the second is for files. The outer loop iterates over the directory list, while the inner loops over the results from using
glob() on the current directory, tossing directories and files into their respective arrays. Rough example:
Code: Select all
$directories = array($directory);
$files = array();
for($dir = 0; $dir < count($directories); $dir++) {
$data = glob($directories[$dir] . DIRECTORY_SEPARATOR . '*');
foreach($data as $key => $file) {
if(is_file($file)) {
$files[] = $file;
} elseif(is_dir($file)) {
$directories[] = $file;
}
}
if(!$recursion) {
break;
}
}
There's a flag at the end there that allows you to switch recursive searching on and off..
Posted: Thu Jan 05, 2006 4:58 pm
by Extremest
ok I am still learning here. LOL... How do I implement that for the start directory.
Posted: Thu Jan 05, 2006 5:11 pm
by Extremest
ok figured that out. It is not listing any files. Only the directory name that is in the main directory.
Posted: Thu Jan 05, 2006 5:20 pm
by Extremest
ok removing the recursion fixed it. Is there a way I can have it remove the dir names that have no file name behind them? That way I just have an array of the dir and filename for the ones that have files. That way I can have my other script go through the array and open the files.
Posted: Thu Jan 05, 2006 5:25 pm
by Extremest
ok I am an idiot. I was cehcking the wrong array. It works perfect now. Should be what I need think you very much.
Posted: Fri Jan 06, 2006 4:57 am
by dude81
gr8 today I learnt one new fucntion glob().
Thanks feyd