M.E*_*M.E 46 php directory loops
我需要在子目录中的所有文件中创建一个循环.你可以帮我构建我的代码,如下所示:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
Run Code Online (Sandbox Code Playgroud)
你能帮忙吗,PLZ?
Mic*_*cki 141
将RecursiveDirectoryIterator与RecursiveIteratorIterator结合使用.
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
Run Code Online (Sandbox Code Playgroud)
GSt*_*Sto 10
如果你的子目录有子目录,你可能想要使用递归函数
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
Run Code Online (Sandbox Code Playgroud)
没有测试代码,但这应该接近你想要的.
小智 7
您需要添加递归调用的路径.
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
Run Code Online (Sandbox Code Playgroud)
我喜欢glob它的通配符:
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Run Code Online (Sandbox Code Playgroud)
但是如果你有一个复杂的文件夹结构RecursiveDirectoryIterator肯定是解决方案.
| 归档时间: |
|
| 查看次数: |
62433 次 |
| 最近记录: |