2016-07-04 3 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

* x *の代わりに* n *を使用するように質問を更新しました。整数に近い感じです。また、文法的な修正を加えました。 – 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持つすべてのファイルを読み、
  • スライスファイル
  • の最初(最新) $x番号を降順 filectime()is_file()
  • ソートファイルをフィルタリングします
関連する問題