2016-07-04 85 views
-1

如何获取PHP中目录中最后X个文件?获取目录中最后X个文件

我使用此代码获取最后一个文件,但我如何获得最后X个文件?

我的代码:

$path = "/path/test/"; 

$latest_ctime = 0; 
$latest_filename = '';  

$d = dir($path); 
while (false !== ($entry = $d->read())) { 
    $filepath = "{$path}/{$entry}"; 
    // could do also other checks than just checking whether the entry is a file 
    if (is_file($filepath) && filectime($filepath) > $latest_ctime) { 
     $latest_ctime = filectime($filepath); 
     $latest_filename = $entry; 
    } 
} 
+0

你最后一个“X”文件是什么意思? – Shank

+0

获取最后10个文件例如 –

+0

我更新了您的问题,使用* n *而不是* x *:感觉更像是一个整数。也做了一些小的文法修正。 – trincot

回答

1
<?php 
$arr = array(); 
$path = "/Users/alokrajiv/Downloads/"; 
$d = dir($path); 
if ($handle = opendir($path)) { 
    while (false !== ($entry = readdir($handle))) { 
     if ($entry != "." && $entry != "..") { 
      $filepath = "{$path}{$entry}"; 
      $tmp = array(); 
      $tmp[0] = $filepath; 
      $tmp[1] = filemtime($tmp[0]); 
      array_push($arr, $tmp); 
     } 
    } 
    closedir($handle); 
} 
function cmp($a, $b){ 
    $x = $a[1]; 
    $y = $b[1]; 
    if ($x == $y) { 
     return 0; 
    } 
    return ($x > $y) ? -1 : 1; 
} 
usort($arr, 'cmp'); 
$x = 10; 
while(count($arr)>$x){ 
    array_pop($arr); 
} 
var_dump($arr); //has last modified 10 files 

排序按降序然后弹出,直到10个元素被保留。

+1

谢谢你的帮助! –

1

可能有点简单:

$files = array_filter(glob("$path/*.*"), 'is_file'); 
array_multisort(array_map('filectime', $files), SORT_DESC, $files); 
$result = array_slice($files, 0, $x); 
  • 阅读所有文件​​3210与is_file()
  • 文件排序筛选上filectime()
  • 片中的第一(最新)$x文件