我希望我的脚本能递归地扫描,
$files = scandir('/dir');
foreach($files as $file){
if(is_dir($file)){
echo '<li><label class="tree-toggler nav-header"><i class="fa fa-folder-o"></i>'.$file.'</label>';
$subfiles = scandir($rooturl.'/'.$file);
foreach($subfiles as $subfile){
// and so on and on and on
}
echo '<li>';
} else {
echo $file.'<br />';
}
}
我想循环这个方法,对于scandir找到的每个目录,它会在该目录中找到的文件夹上运行另一个scandir,
所以dir 'A'包含dir 1/2/3,它现在应该scandir(1),scandir(2),scandir(3)等等。
我怎样才能管理实现这一点很容易没有复制粘贴代码一遍又一遍地在每一个foreach?
编辑:因为答案和我已经试过的几乎一样,我会更新一下这个问题。
使用此脚本,我需要创建一个treeview列表。使用当前发布的脚本,会发生以下get的echo'd:
/images/dir1/file1.png
/images/dir1/file2.png
/images/dir1/file3.png
/images/anotherfile.php
/data/uploads/avatar.jpg
/data/config.php
index.php
我真正需要的是:
<li><label>images</label>
<ul>
<li><label>dir1</label>
<ul>
<li>file1.png</li>
<li>file2.png</li>
<li>file3.png</li>
</ul>
</li>
<li>anotherfile.php</li>
</ul>
</li>
<li><label>data</label>
<ul>
<li><label>uploads</label>
<ul>
<li>avatar.jpg</li>
</ul>
</li>
<li>config.php</li>
</ul>
</li>
<li>index.php</li>
等等,谢谢你已经张贴的答案!
7条答案
按热度按时间7xzttuei1#
我知道这是一个老问题,但我写了一个更实用的版本。它不使用全局状态,而是使用纯函数来解决问题:
0g0grzrc2#
你可以通过这种方式递归地扫描目录,目标是你最顶层的目录:
您可以根据您的需要轻松调整此功能。例如,如果要使用此功能删除目录及其内容,您可以执行以下操作:
你不能这样做的方式你这样做.下面的函数得到递归的所有目录,子目录这么深,你想要的和它们的内容:
将路径传递给函数:
$filedata是一个数组,其中包含所有已创建的目录和子目录及其内容。此函数可以让您扫描目录结构($directory_depth),并且可以摆脱所有无聊的隐藏文件(例如'.','..')
现在您所要做的就是使用返回的数组,即完整的树结构,按照您的喜好在视图中排列数据。
你正在尝试做的实际上是一种文件管理器,正如你所知道的,有很多这样的东西在野外,开源和免费。
我希望这对你有帮助,祝你圣诞快乐。
0ve6wy6x3#
前一个函数的变体,使用三元运算符使函数更短,使用splat(或spread)运算符解包array_push的数组。
旧版
我知道这是旧的,但我想展示一个稍微不同的版本的其他答案。使用array_diff丢弃“.”和“..”文件夹。还有+运算符合并2个数组(我很少看到这个使用,所以它可能对某人有用)
nbysray54#
虽然这个问题很老了,但我的回答可以帮助访问这个问题的人。
这将递归地扫描目录和子目录,并将输出存储在全局变量中。
jv2fixgn5#
创建一个扫描函数并将其命名为recursively ...
例如:
你可以对这个函数做很多变化,比如打印一个'li'标签而不是PHP_EOL,来创建一个树视图。
[编辑]
u0njafvf6#
现代方式:
wwwo4jvm7#