简体   繁体   English

如何从PHP目录中获取X最新文件?

[英]How to get X newest files from a directory in PHP?

The code below is part of a function for grabbing 5 image files from a given directory. 下面的代码是从给定目录中获取5个图像文件的函数的一部分。

At the moment readdir returns the images 'in the order in which they are stored by the filesystem' as per the spec . 目前,readdir根据规范按照文件系统存储的顺序返回图像。

My question is, how can I modify it to get the latest 5 images? 我的问题是,如何修改它以获取最新的5张图像? Either based on the last_modified date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.). 基于last_modified日期或文件名(看起来像0000009-16-5-2009.png,0000012-17-5-2009.png等)。

if ( $handle = opendir($absolute_dir) )
{
    $i = 0;
    $image_array = array();

    while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) )
    {
        if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' ) 
        {
            $image_array[$i]['url'] = $relative_dir . $file;
            $image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
        }

        $i++;
    }
    closedir($handle);
}

If you want to do this entirely in PHP, you must find all the files and their last modification times: 如果要在PHP中完全执行此操作,则必须找到所有文件及其上次修改时间:

$images = array();
foreach (scandir($folder) as $node) {
    $nodePath = $folder . DIRECTORY_SEPARATOR . $node;
    if (is_dir($nodePath)) continue;
    $images[$nodePath] = filemtime($nodePath);
}
arsort($images);
$newest = array_slice($images, 0, 5);

If you are really only interested in pictures you could use glob() instead of soulmerge's scandir: 如果你真的只对图片感兴趣,你可以使用glob()而不是soulmerge的scandir:

$images = array();
foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) {
    $images[$filename] = filemtime($filename);
}
arsort($images);
$newest = array_slice($images, 0, 5);

Or you can create function for the latest 5 files in specified folder. 或者,您可以为指定文件夹中的最新5个文件创建功能。

private function getlatestfivefiles() {
    $files = array();
    foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) {
        $files[$filename] = filemtime($filename);
    }
    arsort($files);

    $newest = array_slice($files, 0, 5);
    return $newest;  
}

btw im using CI framework. 顺便说一句,我正在使用CI框架。 cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM