How do I put every file name on the root directory and and all the file names in each sub folder into an array in php?
1
-
8What about reading the documentation? What about googling for a suggestion? This forum is not for having someone else do your homework. First try yourself to solve the problem, and if you really are stuck, then is the time to write a question here. A good question, containing teh attempt you did until then, code, problem description and all.arkascha– arkascha2012-09-09 15:22:04 +00:00Commented Sep 9, 2012 at 15:22
Add a comment
|
5 Answers
Use scandir() and you'll find a recursive function for sub-directories as well as tons of other examples to achieve what you want.
Comments
I have always preferred DirectoryIterator and RecursiveDirectoryIterator.
Here is an example:
function drawArray(DirectoryIterator $directory)
{
$result=array();
foreach($directory as $object)
{
if($object->isDir()&&!$object->isDot())
{
$result[$object->getFilename()]=drawArray(new DirectoryIterator($object->getPathname()));
}
else if($object->isFile())
{
$result[]=$object->getFilename();
}
}
return $result;
}
$array=drawArray(new DirectoryIterator('/path'));
print_r($array);
Have a look at glob() [and give condolence to your RAM by the way if you really want to skim all your files].
Comments
This is how I do it.
/**
Recursively returns all the items in the given directory alphabetically as keys in an array, optionally in descending order.
If a key has an array value it's a directory and its items are in the array in the same manner.
*/
function scandir_tree($directory_name, $sort_order = SCANDIR_SORT_ASCENDING, $_recursed = false)
{
if (!$_recursed || is_dir($directory_name))
{
$items = array_diff(scandir($directory_name, (int) $sort_order), ['.', '..']);
$tree = [];
foreach ($items as $item)
{
$tree[$item] = scandir_tree($directory_name . $item, $sort_order, true);
}
return $tree;
}
return $directory_name;
}