2010-05-27 58 views
1

我正在查找代码,它递归地列出目录中最近的五个文件。通过PHP递归获取最新的文件

这是非递归的代码,将是完美的我,如果它是递归的:

<?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 */ 
} 
?> 

它可以修改它以递归扫描目录?

+1

你是什么意思递归?你想列出给定目录及其所有子目录中最近触及的五个文件? – Dereleased 2010-05-27 20:00:32

+0

是的,是的! “列出给定目录中最近触及的五个文件及其所有子目录” – Peter 2010-05-27 20:21:02

回答

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); 
} 
+0

' glob'不是递归的。 – 2013-09-17 19:57:42

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; 
} 

但我喜欢字节的使用的​​3210,所以这里是他的稍微修改版本,返回相同的格式:

function top5modsEx($dir) { 
    $mods = array(); 
    foreach (glob($dir . '/*') as $f) { 
     $mods[filemtime($f)] = $f; 
    } 
    krsort($mods); 
    return array_slice($mods, 0, 5, true); 
} 

这将返回文件被修改为数组元素键的时间(UNIX时间戳格式)。

+0

像魅力一样工作!有没有办法从搜索中排除文件? – Peter 2010-05-30 13:29:37

+0

|| $ item =='exclude this'---这是解决方案。 非常感谢你! – Peter 2010-05-30 13:35:40