Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取目录中最后X个文件数_Php - Fatal编程技术网

Php 获取目录中最后X个文件数

Php 获取目录中最后X个文件数,php,Php,如何在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 che

如何在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;
   }
}

可能更简单一些:

$files  = array_filter(glob("$path/*.*"), 'is_file');
array_multisort(array_map('filectime', $files), SORT_DESC, $files);
$result = array_slice($files, 0, $x);
  • 使用
    glob()
    读取所有文件,并使用
    is\u file()
  • filectime()上的文件进行降序排序
  • 切片第一个(最新)
    $x
    文件数

你所说的最后一个“X”文件是什么意思?以最后10个文件为例,我更新了你的问题,用n代替了X:感觉更像一个整数。还做了一些小的语法修改。哇,3行30行,太神奇了!在编辑之前,请将使用的
X
作为答案回滚到
N
。感谢您的帮助!
$files  = array_filter(glob("$path/*.*"), 'is_file');
array_multisort(array_map('filectime', $files), SORT_DESC, $files);
$result = array_slice($files, 0, $x);