0

我有一个读取目录内容的函数,让我们调用它/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以真/假为值的常量。

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_file非常file_exists小,我更喜欢这种语法中的 file_exists,因为我检查它是否存在,而不是它是否是一个文件。

4

1 回答 1

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不存在,如果存在则将其添加到数组中。

于 2013-09-11T13:12:54.967 回答