Che*_*eso 3 php directory recursion parsing loops
我希望修改这个PHP代码,在具有未知数量的子目录的单个已知目录上执行递归"搜索和显示图像".
这是我扫描单个目录并将文件回显到html的代码:
<?php
foreach(glob('./img/*.jpg') as $filename)
{
echo '<img src="'.$filename.'"><br>';
}
?>
Run Code Online (Sandbox Code Playgroud)
假定基本目录$base_dir="./img/";包含具有未知数量的子目录和它们自己的子目录的层,这些子目录都仅包括.jpg文件类型.
基本上需要构建子目录的所有路径的数组.
前段时间我写了这个函数来遍历目录层次结构.它将返回给定文件夹中包含的所有文件路径(但不返回文件夹路径).您应该可以轻松地修改它以仅返回名称以.jpg结尾的文件.
function traverse_hierarchy($path)
{
$return_array = array();
$dir = opendir($path);
while(($file = readdir($dir)) !== false)
{
if($file[0] == '.') continue;
$fullpath = $path . '/' . $file;
if(is_dir($fullpath))
$return_array = array_merge($return_array, traverse_hierarchy($fullpath));
else // your if goes here: if(substr($file, -3) == "jpg") or something like that
$return_array[] = $fullpath;
}
return $return_array;
}
Run Code Online (Sandbox Code Playgroud)