簡體   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