繁体   English   中英

PHP scandir-多个目录

[英]PHP scandir - multiple directories

我正在创建一个WordPress插件,该插件允许用户将排序规则应用于特定模板(页面,存档,单个等)。 我正在使用PHP scandir填充页面列表,如下所示:

$files = scandir(get_template_directory());

问题是我将single.php模板保留在“ / single”子文件夹中,因此上述函数未调用这些模板。

如何在scandir函数中使用多个目录(也许是数组?),或者需要其他解决方案?

所以基本上我正在尝试:

$files  =   scandir( get_template_directory() AND get_template_directory().'/single' );

我当前的解决方案(不是很优雅,因为每个循环需要2个):

        function query_caller_is_template_file_get_template_files()
            {
                $template_files_list    =   array();

                $files          =   scandir(get_template_directory());
                $singlefiles    =   scandir(get_template_directory().'/single');

                foreach($files  as  $file)
                    {
                        if(strpos($file, '.php')    === FALSE)
                            continue;

                        $template_files_list[]  =   $file;
                    }

                foreach($singlefiles  as  $singlefile)
                    {
                        if(strpos($file, '.php')    === FALSE)
                            continue;

                        $template_files_list[]  =   $singlefile;
                    }

                return $template_files_list;
            }

首先,您所做的没有任何错误 您有两个目录,因此您做两次相同的事情。 当然,您可以使它看起来更干净一些,并避免使用公然的复制粘贴:

$files = array_merge(
    scandir(get_template_directory()),
    scandir(get_template_directory().'/single')
);

现在,只需遍历单个数组即可。

在你的情况下,获取文件列表递归是没有意义的,因为有可能是你想要检查子目录。 如果您确实想递归到子目录,则opendir()readdir()以及is_dir()会允许您构建递归扫描函数。

您可以使用array_filter()将事件'.php'过滤器部分收紧。

$files = array_filter($files, function($file){
    return strpos($file, '.php');
});

在这里,我假设文件应该以.php开头,因此您对创建列表并不真正感兴趣(因为在这种情况下, strpos()会返回伪造的值0 )。 我还假设您确定中间没有.php

就像template.php.bak一样,因为您将使用版本控制来进行类似的操作。

但是,如果有这种可能,您可能需要加紧检查,以确保.php位于文件名的末尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM