【问题标题】:Get latest 15 files in a directory that are recently added to it php [duplicate]获取最近添加到它的目录中的最新15个文件php [重复]
【发布时间】:2023-12-11 05:45:02
【问题描述】:

假设有一个名为“abc”的目录

此目录包含许多文件。在所有这些文件中,我只想要 php 中的数组中最新的“X”或最新的 15 个文件(如果可能,使用 glob 函数)。

每一个帮助都会非常显着。

【问题讨论】:

  • 你有没有尝试过?
  • 感谢大家宝贵的时间和帮助。不过,我自己试了,也得到了答案,我就把它作为答案贴出来

标签: php file glob


【解决方案1】:
// directory for searching files

$dir = "/etc/php5/*";

// getting files with specified four extensions in $files

$files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);

// will get filename and filetime in $files

$files = array_combine($files, array_map("filemtime", $files));

// will sort files according to the values, that is "filetime"

arsort($files);

// we don't require time for now, so will get only filenames(which are as keys of array)

$files = array_keys($files);

$starting_index = 0;
$limit = 15;

// will limit the resulted array as per our requirement

$files = array_slice($files, $starting_index,$limit);

// will print the final array

echo "Latest $limit files are as below : ";
print_r($files);

如果我错了,请改进我

【讨论】:

  • 这很好用。我知道这有点老了,但你应该把代码放到标签中。
【解决方案2】:

使用此处发布的功能:http://code.tutsplus.com/tutorials/quick-tip-loop-through-folders-with-phps-glob--net-11274

    $dir = "/etc/php5/*";

    // Open a known directory, and proceed to read its contents
    foreach(glob($dir) as $file) 
    {
        echo "filename: $file : filetype: " . filetype($file) . "<br />";
    }

并在 foreach 循环中使用 filetime() 函数作为 IF 语句。:http://php.net/manual/en/function.filemtime.php

【讨论】:

    【解决方案3】:

    一种比 glob 更好的方法是使用RecursiveDirectoryIterator

      $dir = new \RecursiveDirectoryIterator('path/to/folder', \FilesystemIterator::SKIP_DOTS);
        $it  = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
        $it->setMaxDepth(99); // search for other folders and they child folders
        $files = [];
    
        foreach ($it as $file) {
            if ($file->isFile()) {
                var_dump($file);
            }
        }
    

    或者如果你仍然想用 glob 来做

    $files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
    foreach($files as $file) {
       var_dump($file);
    }
    

    【讨论】:

      最近更新 更多