Php 获取目录中最后X个文件数
如何在PHP中获取目录中最后X个文件 我使用此代码获取最后一个文件,但如何获取最后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
$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);