我有一个读取目录内容的函数,我们称之为/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_file
和 file_exists
之间的差异非常小,我更喜欢file_exists这种语法,因为我检查它是否存在,而不是它是否是一个文件。
$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
为 true 时,它会检查它是否具有_mobile
或_mobile
版本是否存在,如果是,则将其添加到数组中。如果 IS_MOBILE_USER 为 false,它只是检查_mobile
是否存在,如果是,则将其添加到数组中。