PHP解析文件路径的目录和子目录,仅限jpg图像类型的名称 [英] PHP parse directory and subdirectories for file paths and names of only jpg image types

查看:109
本文介绍了PHP解析文件路径的目录和子目录,仅限jpg图像类型的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找修改这个php代码来执行一个递归的搜索和显示图像在单个已知的目录,具有未知的子目录数量。

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.

这是我扫描单个目录的代码,并将文件回显到html:

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>';
    }
?>

鉴于基本目录 $ base_dir =./ img /; 包含子目录,其子目录数量和层次不一致,全部仅包含.jpg文件类型。

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.

推荐答案

前段时间我写了这个函数来遍历目录层次结构。它将返回给定文件夹中包含的所有文件路径(而不是文件夹路径)。你应该很容易地修改它,只返回名字以.jpg结尾的文件。

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;
}

这篇关于PHP解析文件路径的目录和子目录,仅限jpg图像类型的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆