我想只搜索和列出特定文件夹,无论这些文件夹有多深。
例如,下面是我如何构建它们,
local/
app/
master/
models/
views/
slaves/
models/
views/
scr/
models/
index.php
我只想将models
的文件夹列入数组
local/app/master/models/
local/app/slaves/models/
local/models/
我的工作代码,
$directories = array();
$results = array_diff( scandir("local"), array(".", "..") );
foreach ($results as $result)
{
if (is_dir("local/".$result)) {
$directories[] = $result;
}
}
var_dump($directories);
结果,
array
0 => string 'app' (length=3)
1 => string 'models' (length=6)
2 => string 'src' (length=3)
有什么想法吗?
答案 0 :(得分:2)
您只扫描一级深度,而不是检查文件夹/文件的名称。相反,您需要递归扫描。尝试这样的事情。我没有测试过这段代码 - 但是你明白了。
$directories = array();
get_directories('local', $directories);
print_r($directories);
function get_directories($path, &$directories)
{
$dirs = scandir($path)
foreach($dirs as $d)
{
if(is_dir("$path/$d")
{
if($d == 'model')
$directories[] = "$path/$d";
elseif($d != '.' && $d != '..')
get_directories("$path/$d", $directories);
}
}
}
同时,如果您不需要在PHP中执行此操作,但只需查找所有目录model
,则可以使用shell命令find
轻松完成此操作:
$ find local/ -name model -type d
答案 1 :(得分:1)
// Create an object that allows us to iterate directories recursively
// Stolen from here:
// http://www.php.net/manual/en/class.recursivedirectoryiterator.php#102587
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::CHILD_FIRST);
// This will hold the result
$result = array();
// Loop the directory contents
foreach ($iterator as $path) {
// If object is a directory and matches the search term ('models')...
if ($path->isDir() && $path->getBasename() === 'models') {
// Add it to the result array
$result[] = (string) $path;
}
}
print_r($result);
答案 2 :(得分:1)
这是另一种没有递归的解决方案,它可以在php 4以及php 5中运行
<?php
$dir ='local';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
$dir .= '/*';
if (!$d) {
$d =$dirs;
} else {
$d=array_merge($d,$dirs);
}
}
$dir_to_match = 'models';
$result = array();
foreach ($d as $dir_name) {
if (preg_match('#/' . $dir_to_match . '$#', $dir_name)) {
$result[] = $dir_name;
}
}
var_dump($result);
?>