如何将根目录中的每个文件名以及每个子文件夹中的所有文件名放入php中的数组中?
问问题
7040 次
5 回答
4
Use scandir() and you'll find a recursive function for sub-directories as well as tons of other examples to achieve what you want.
于 2012-09-09T15:29:38.873 回答
3
我一直偏爱DirectoryIterator
和RecursiveDirectoryIterator
。
这是一个例子:
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);
于 2012-09-09T15:39:48.293 回答
1
看看glob()
[如果您真的想浏览所有文件,请顺便向您的 RAM 表示哀悼]。
于 2012-09-09T15:23:42.957 回答
1
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;
}
于 2012-09-09T15:30:23.037 回答
1
尝试这个:
$ar=array();
$g=scandir('..');
foreach($g as $x)
{
if(is_dir($x))$ar[$x]=scandir($x);
else $ar[]=$x;
}
print_r($ar);
于 2012-09-09T15:35:05.530 回答