显示数组中目录内容的“漂亮输出”
我使用以下代码来获取目录及其子目录的数组,其中每个目录都包含文件类型扩展名:png。它工作得很好,但我需要能够以列表样式格式输出数组的结果,例如
* Test
-> test2.png
-> test1.png
* subfolder
-> test3.png
* sub sub folder
-> test4.png
等
代码:
$filter=".png";
$directory='../test';
$it=new RecursiveDirectoryIterator("$directory");
foreach(new RecursiveIteratorIterator($it) as $file){
if(!((strpos(strtolower($file),$filter))===false)||empty($filter)){
$items[]=preg_replace("#\\\#", "/", $file);
}
}
结果数组示例:
array (
0 => '../test/test2.png',
1 => '../test/subfolder/subsubfolder/test3.png',
2 => '../test/subfolder/test3.png',
3 => '../test/test1.png',
)
实现所需结果的最佳方法是什么?
I'm using the following code to get an array of directories and their sub-directories where each contain file type extension: png. It works great but I need to be able to output the results of the array in a list style format e.g.
* Test
-> test2.png
-> test1.png
* subfolder
-> test3.png
* sub sub folder
-> test4.png
etc
Code:
$filter=".png";
$directory='../test';
$it=new RecursiveDirectoryIterator("$directory");
foreach(new RecursiveIteratorIterator($it) as $file){
if(!((strpos(strtolower($file),$filter))===false)||empty($filter)){
$items[]=preg_replace("#\\\#", "/", $file);
}
}
Example array of results:
array (
0 => '../test/test2.png',
1 => '../test/subfolder/subsubfolder/test3.png',
2 => '../test/subfolder/test3.png',
3 => '../test/test1.png',
)
What would be the best way of achieving the desired result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在你的 if 子句中,尝试:
这应该会给你一个接近你想要的输出。但是,
getPathName
输出绝对路径。In your if-clause, try:
This should give you an output close to the one you desire. However,
getPathName
outputs absolute paths.如果您想在目录之前显示文件,那么您不能简单地在循环中执行此操作,因为您不知道稍后是否会显示更多文件。
您需要将数据聚合在树(由路径组件索引的数组的数组)中或对其进行排序。
它应该为您提供如下结构:
这将很容易使用(当然,这有点违背了
RecursiveDirectoryIterator
的目的。您可以通过递归地使用常规DirectoryIterator
来获得相同的结果)。或者,如果您按深度对路径进行排序(编写比较函数),那么您只需通过使用适当的缩进打印最后一个路径组件即可输出它。
If you want to display files before directories, then you can't do it simply in a loop, because you won't know if more files would come later.
You need to aggregate the data in a tree (array of arrays indexed by path component) or sort it.
It should give you structure such as:
That will be straightforward to work with (of course that kinda defeats the purpose of
RecursiveDirectoryIterator
. You could get the same by recursively using regularDirectoryIterator
).Or if you sort paths by depth (write your comparison function), then you'll be able to output it simply by printing last path component with appropriate indentation.