从图像和文件的文件树中创建一个选择下拉列表使用 PHP 的子目录

发布于 2024-09-27 03:37:15 字数 951 浏览 0 评论 0原文

我正在创建一个 WordPress 元框,我需要扫描模板中包含图像的子目录目录,并将它们添加到选择下拉列表中,以便我可以在模板中使用文件名。

图像当前在文件夹中的排列方式如下:

父文件夹
|_ 辅助文件夹
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif
|_ 辅助文件夹
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif

理想情况下,我想将该结构保留在我的选择下拉列表中。

辅助文件夹。
   |_ Image.png

我一直在使用这个:

function get_dir_path(){
    return dirname(__FILE__).'/library/images';
}
$largeImagesdir = get_dir_path() . '/960x345/';


    if ($dh = opendir($largeImagesdir)) {
        while (($file = readdir($dh)) !== false) {
            $lfiles .= '<option>' . $file . '</option>';
        }
        closedir($dh);
    }

    $buildbox .= '<select>' . $lfiles . '</select>';

但是,这当然只有在我将 $largeImagesdir var 设置为子目录之一时才有效...

任何人都可以帮忙吗?

I'm creating a wordpress meta box and I need to scan a directory of subdirectories containing images within my template and add these to a select dropdown so I can use the filename in my template.

The images are currently arranged in the folder like this:

Parent Folder
|_ Secondary Folder
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif
|_ Secondary Folder
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif

Ideally I'd like to keep that structure in my select dropdown ie.

Secondary Folder .
   |_ Image.png

I've been using this:

function get_dir_path(){
    return dirname(__FILE__).'/library/images';
}
$largeImagesdir = get_dir_path() . '/960x345/';


    if ($dh = opendir($largeImagesdir)) {
        while (($file = readdir($dh)) !== false) {
            $lfiles .= '<option>' . $file . '</option>';
        }
        closedir($dh);
    }

    $buildbox .= '<select>' . $lfiles . '</select>';

However this of course only works if I set the $largeImagesdir var to be one of the sub directories...

Can anyone help?

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

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

发布评论

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

评论(1

傲性难收 2024-10-04 03:37:15

你需要一个循环内有一个循环。假设只有 2 级目录,在您的 while 中检查 $file 是否是使用 is_dir() 的子目录,如果是,则执行 readdir() 也可以构建其选项。

然后,您可以通过 optgroup 来区分子目录

如果您需要多个不同级别的子目录,则需要一个递归函数来处理它。 此处显示的是一个很好的开始观点。

You need a loop inside a loop. Assuming only 2 levels of directories, in your while check if $file is a subdirectory with is_dir(), and if yes do a readdir() on that too to get its options built.

Then, you can distinguish the subdirectories by optgroup in your <select> element.

If you need multiple varying levels of subdirectories you'll need a recursive function to take care of it. The one shown here is a good starting point.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文