我正在寻找递归列出目录中五个最新文件的代码。
这是非递归代码,如果它是递归的,那么对我来说将是完美的:
<?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 */
}
?>
是否可以修改它以递归扫描目录?
这是我的第一个版本(经过测试,工作):
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;
}
但我喜欢 byte 的用法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 时间戳格式)作为数组中元素的键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)