使用 RecursiveDirectoryIterator 将目录和文件列出到数组中?
我有一个具有以下结构的目录:
- main/
- |- 图片/
- |-- file1.jpg
- |-- file2.jpg
- |-- file3.jpg
- |- 文档/
- |-- 私有/
- |--- blahblahblah.docx
- |-- 测试.doc
- |-- 测试.xls
- |-- 测试.txt
- |-- 私有/
- |- 图片/
我可以创建一个函数来完成工作,但 RecursiveDirectoryIterator 类速度更快,内存使用量更少时间。如何使用 RecursiveDirectoryIterator 将这些目录列出到数组中,如下所示:
array(
"main/" => array(
"images/" => array(
"file1.jpg",
"file2.jpg",
"file3.jpg"
),
"documents/" => array(
"private/" => array(
"blahblahblah.docx"
),
"test.doc",
"test.xls",
"test.txt"
)
)
)
I'm having a directory with this structure :
- main/
- |- images/
- |-- file1.jpg
- |-- file2.jpg
- |-- file3.jpg
- |- documents/
- |-- private/
- |--- blahblahblah.docx
- |-- test.doc
- |-- test.xls
- |-- test.txt
- |-- private/
- |- images/
I can create a function to complete the work but the RecursiveDirectoryIterator class is much faster and less memory usage this time. How can I use RecursiveDirectoryIterator to list these directory into an array like this :
array(
"main/" => array(
"images/" => array(
"file1.jpg",
"file2.jpg",
"file3.jpg"
),
"documents/" => array(
"private/" => array(
"blahblahblah.docx"
),
"test.doc",
"test.xls",
"test.txt"
)
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,要递归地迭代
RecursiveIterator
,您需要一个RecursiveIteratorIterator
(我知道这看起来多余,但事实并非如此)...但是,对于您的特定情况(您希望生成一个结构而不是仅仅访问所有节点) ),我认为常规递归会更适合...
编辑它以与非递归迭代器一起使用...
Well, to recursively iterate over the
RecursiveIterator
, you need aRecursiveIteratorIterator
(I know it seems redundant, but it's not)...However, for your particular case (Where you're looking to generate a structure rather than just visit all of the nodes), I think regular recursion would be better suited...
Edit it to work with non-recursive-iterators...
为了给其他人记录,我将一个类(
RecursiveDirectoryIterator
)变成了一个要点,它可以读取一个目录及其所有子目录并输出一个 JSON 或只是一个数组。https://gist.github.com/jonataswalker/3c0c6b26eabb2e36bc90
以及输出的树查看器
< a href="http://codebeautify.org/jsonviewer/067c13" rel="nofollow">http://codebeautify.org/jsonviewer/067c13
Just to record for others, I've turned into a gist a class (
RecursiveDirectoryIterator
) that can read a directory with all its children and output a JSON or just an array.https://gist.github.com/jonataswalker/3c0c6b26eabb2e36bc90
And a tree viewer of the output
http://codebeautify.org/jsonviewer/067c13