PHP读取子目录并循环文件如何?
我需要创建一个循环遍历子目录中的所有文件。你能帮我构造我的代码吗:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
将 RecursiveDirectoryIterator 与 RecursiveIteratorIterator 结合使用。
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.
您需要将路径添加到递归调用中。
You need to add the path to your recursive call.
您可能想为此使用递归函数,以防您的子目录有子子目录
没有测试代码,但这应该接近您想要的。
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
didn't test the code, but this should be close to what you want.
我喜欢带有通配符的
glob
:详细信息和更复杂的场景。< /a>
但如果您有复杂的文件夹结构
RecursiveDirectoryIterator
绝对是解决方案。I like
glob
with it's wildcards :Details and more complex scenarios.
But if You have a complex folders structure
RecursiveDirectoryIterator
is definitively the solution.来吧,先自己尝试一下吧!
你需要什么:
当然还有
foreach
http ://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
Come on, first try it yourself!
What you'll need:
and of course
foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
另一种解决方案读取子目录和子文件(设置正确的文件夹名称):
Another solution to read with sub-directories and sub-files (set correct foldername):
如果我们可以安全地消除任何名为 的项目,则对 John Marty 发布的内容进行小修改。或者 ..
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..