我正在寻找以递归方式列出目录中五个最新文件的代码。
这是非递归代码,如果它是递归的,对我来说是完美的:
<?php
$show = 0; // Leave as 0 for all
$dir = 'sat/'; // Leave as blank for current
if($dir) chdir($dir);
$files = glob( '*.{html,php,php4,txt}', GLOB_BRACE );
usort( $files, 'filemtime_compare' );
function filemtime_compare( $a, $b )
{
return filemtime( $b ) - filemtime( $a );
}
$i = 0;
foreach ( $files as $file )
{
++$i;
if ( $i == $show ) break;
echo $file . ' - ' . date( 'D, d M y H:i:s', filemtime($file) ) . '<br />' . "\n"; /* This is the output line */
}
?>
可以修改它以递归扫描目录吗?
答案 0 :(得分:2)
这是我的第一个版本(已测试,正在使用):
function latest($searchDir, array $files = array()) {
$search = opendir($searchDir);
$dirs = array();
while($item = readdir($search)) {
if ($item == '.' || $item == '..') { continue; }
if (is_dir($searchDir.'/'.$item)) {
$dirs[] = $searchDir.'/'.$item;
}
if (is_file($searchDir.'/'.$item)) {
$ftime = filemtime($searchDir.'/'.$item);
$files[$ftime] = $searchDir.'/'.$item;
}
}
closedir($search);
if (count($dirs) > 0) {
foreach ($dirs as $dir) {
$files += latest($dir,$files);
}
}
krsort($files);
$files = array_slice($files, 0, 5, true);
return $files;
}
但是我喜欢字节对glob()
的使用,所以这里有一个稍微修改过的版本,以返回相同的格式:
function top5modsEx($dir) {
$mods = array();
foreach (glob($dir . '/*') as $f) {
$mods[filemtime($f)] = $f;
}
krsort($mods);
return array_slice($mods, 0, 5, true);
}
这将返回修改文件的时间(UNIX时间戳格式)作为数组中元素的键。
答案 1 :(得分:1)
这是非常快速和肮脏的,未经测试,但可能会让你开始:
function top5mods($dir)
{
$mods = array();
foreach (glob($dir . '/*') as $f) {
$mods[] = filemtime($f);
}
sort($mods);
$mods = array_reverse($mods);
return array_slice($mods, 0, 5);
}
答案 2 :(得分:0)
在PHP手册中查看此solution。
答案 3 :(得分:0)
编辑:对不起,我没有“递归地”看到该部分。
要首先获取RECENTS文件(例如html),请使用匿名函数进行如下排序:
$myarray = glob("*.*.html");
usort($myarray, function($a,$b){
return filemtime($b) - filemtime($a);
});
要递归获取它,您可以:
function glob_recursive($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
因此,将glob函数替换为:
$myarray = glob_recursive("*.*.html");
usort($myarray, function($a,$b){
return filemtime($b) - filemtime($a);
});