簡體   English   中英

獲取目錄中的最后X個文件

[英]Get the last X number of files in a directory

如何獲取PHP目錄中最后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;
   }
}
<?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個元素。

可能會更簡單一些:

$files  = array_filter(glob("$path/*.*"), 'is_file');
array_multisort(array_map('filectime', $files), SORT_DESC, $files);
$result = array_slice($files, 0, $x);
  • 使用glob()讀取所有文件,並使用is_file()過濾
  • filectime()降序對文件進行排序
  • 切片第一個(最新) $x個文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM