PHP 解析目录和子目录以获取仅 jpg 图像类型的文件路径和名称

发布于 2024-08-23 04:41:52 字数 364 浏览 0 评论 0原文

我希望修改此 php 代码,以在具有未知数量子目录的单个已知目录上执行递归“搜索和显示图像”。

下面是我扫描单个目录并将文件回显为 html 的代码:

<?php 
    foreach(glob('./img/*.jpg') as $filename)
    {
        echo '<img src="'.$filename.'"><br>';
    }
?>

鉴于基本目录 $base_dir="./img/"; 包含数量和层数未知的子目录他们自己的子目录都只包含 .jpg 文件类型。

基本上需要构建一个包含所有子目录路径的数组。

I am looking to modify this php code to do a recursive "search for and display image" on a single, known, directory with an unknown amount of sub-directories.

Here's the code I have that scans a single directory and echoes the files out to html:

<?php 
    foreach(glob('./img/*.jpg') as $filename)
    {
        echo '<img src="'.$filename.'"><br>';
    }
?>

Given that the base directory $base_dir="./img/"; contains sub-directories having unknown amounts and tiers of their own sub-directories which all include only .jpg file types.

Basically need to build an array of all the paths of the sub-directories.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七秒鱼° 2024-08-30 04:41:52

前段时间我写了这个函数来遍历目录层次结构。它将返回给定文件夹中包含的所有文件路径(但不包括文件夹路径)。您应该能够轻松修改它以仅返回名称以 .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;
}

Some time ago I wrote this function to traverse a directory hierarchy. It will return all file paths contained in the given folder (but not folder paths). You should easily be able to modify it to return only files whose name ends in .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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文