可能重复:
Caching readdir()
我设置了自己的网站,以便我拥有干净的网址,文件本身也位于不同级别的文件夹中。为了管理它,我有以下脚本来指导我在页面中更远的地方。
function listFolderFiles($dir,$exclude){
global $flist;
$ffs = scandir($dir);
foreach($ffs as $ff)
{
if(is_array($exclude) and !in_array($ff,$exclude))
{
if($ff != '.' && $ff != '..')
{
if(!is_dir($dir.'/'.$ff))
{
}
if(is_dir($dir.'/'.$ff))
{
listFolderFiles($dir.'/'.$ff,$exclude);
}
if((is_dir($dir.'/'.$ff)) != 1 && strtolower(substr($ff, strrpos($ff, '.') + 1)) == 'php')
{
$name = basename($ff, ".php");
$flist[] .= $name;
}
}
}
}
}
listFolderFiles('content/',array('filelist.php'));
$removing = array('_en','_es');
$pages = str_replace($removing, "", $flist);
unset($dir, $exclude, $flist);
listFolderFiles('content/Beginner/',array('filelist.php'));
$removing = array('_en','_es');
$beginner = str_replace($removing, "", $flist);
unset($dir, $exclude, $flist);
listFolderFiles('content/Intermediate/',array('filelist.php', $beginner));
$removingi = array('_en','_es');
$intermediate = str_replace($removingi, "", $flist);
unset($dir, $exclude, $flist);
listFolderFiles('content/Advanced/',array('filelist.php', $beginner));
$removinga = array('_en','_es');
$advanced = str_replace($removinga, "", $flist);
是否有更快的方式来执行此代码,因为它目前在每个页面加载中使用,我只需要在添加新文件时更新它。
答案 0 :(得分:1)
除了算法改进之外,这是一个很好的缓存候选者。看起来它可以像序列化数组并将其放入文件一样简单。然后,您可以决定过期策略。伪代码:
if(!file_exists(CACHE_NAME) || dir_cache_expired(CACHE_NAME)) {
// ... code to build $dirlist
file_put_contents(CACHE_NAME, serialize($dirlist));
} else {
$dirlist = unserialize(file_get_contents(CACHE_NAME));
}
这样,您只需删除缓存文件即可触发重建缓存。