获取移动版本(如果存在),否则为普通文件

时间:2013-09-11 13:10:11

标签: php performance filter directory

我有一个读取目录内容的函数,我们称之为/dir/css/ 在这个目录中,我有一些文件,其中我不知道文件名,这可以是随机的:

[0] filename.css
[1] filename_mobile.css
[2] otherfile.css
[3] otherfile_mobile.css
[4] generalfile.css
[5] otherGeneralfile.css

我定义了一个常量IS_MOBILE_USER,其值为true / false。

IS_MOBILE_USER===true我想要带有移动后缀的文件,或者没有移动版本的文件。

filename_mobile.css    <- take mobile variant instead of filename.css
otherfile_mobile.css   <- take mobile variant instead of otherfile.css
generalfile.css      <- take this, no _mobile variant present
otherGeneralfile.css <- take this, no _mobile variant present

任何能够推动我朝着正确方向前进的人?不需要用代码编写,我正在寻找一列虽然(但代码是完全可以接受的:P)

编辑:性能很重要,否则我会创建一个循环遍历数组的函数,以确保一切都匹配。但阵列很慢:)


这就是我现在所处的位置,这给了我一个没有_mobile文件的数组。现在我想添加一些代码,如果可能的话,它会给我_mobile变体,而不必再次遍历它。

define('IS_MOBILE_USER', true); // true now, I use this to test, could be false
function scandir4resource($loc, $ext){
    $files = array();
    $dir = opendir($_SERVER['DOCUMENT_ROOT'].$loc);
    while(($currentFile = readdir($dir)) !== false){
        // . and .. not needed
        if ( $currentFile == '.' || $currentFile == '..' ){
            continue;
        }
        // Dont open backup files
        elseif( strpos($currentFile, 'bak')!==false){
            continue;
        }
        // If not mobile, and mobile file -> skip
        elseif( !IS_MOBILE_USER && strpos($currentFile, '_mobile')!==false){
            continue;
        }
        // if mobile, current file doesnt have '_mobile' but one does exist->skip
        elseif( IS_MOBILE_USER && strpos($currentFile, '_mobile')===false 
                && file_exists($_SERVER['DOCUMENT_ROOT'].$loc.str_replace(".".$ext, "_mobile.".$ext, $currentFile)) ){
            continue;
        }
        // If survived the checks, add to array:
        $files[] = $currentFile;
    }
    closedir($dir);
    return $files;
}

我有一个小基准测试,对此函数的10.000调用需要1.2-1.5秒,再次循环需要花费很多时间。

for($i=0; $i<=10000; $i++){
    $files = scandir4resource($_SERVER['DOCUMENT_ROOT']."UserFiles/troep/");
}

最后这是结果: “花了1.8013050556183秒”并保持这个价值 is_filefile_exists之间的差异非常小,我更喜欢这种语法中的file_exists,因为我会检查它是否存在,而不是它是否是文件。

1 个答案:

答案 0 :(得分:2)

$filesArray = glob("/path/to/folder/*.css");
foreach($filesArray as $index => $file) {
   if( stripos($file,"_mobile") !== FALSE || 
       !in_array( str_replace(".css","_mobile.css",$file), $filesArray ) )
     continue;
   unset($filesArray[$index]);
}    

获取所有css文件,取消任何没有“_mobile”但保留那些没有移动替代品的文件。

编辑以使用当前循环

if ( $currentFile == '.' || $currentFile == '..' ) continue;

$isMobile = stripos($currentFile,"_mobile") !== FALSE;
$hasMobileVer = is_file($loc.str_replace(".css","_mobile.css",$currentFile));

if (           
      ( IS_MOBILE_USER && (  $isMobile || !$hasMobileVer )  ) ||
      ( !IS_MOBILE_USER && !$isMobile ) 
   )
   $files[] = $currentFile; 

IS_MOBILE_USER为真时,它会检查它是否有_mobile,或者_mobile版本是否存在,如果是,则将其添加到数组中。 如果IS_MOBILE_USER为false,则只检查_mobile是否不存在,如果是,则将其添加到数组中。