0

I want to get the latest file from a directory, including the subdirectories in it.

I have these folders:

MainFolder
├───Folder1
│       File135646.txt
│       File341324.txt
│
└───Folder2
        File467456.txt
        File745674.txt

I want it to return an array like this, showing the latest to oldest files:

Array ( [0] => Folder1/File135646.txt [1] => Folder2/File467456.txt [2] => Folder2/File745674.txt [3] => Folder1/File341324.txt )

Each element would contain folder/file but the order would be from latest to oldest file. I have tried this, but it doesn't work with subdirectories.

scandir('folder', SCANDIR_SORT_ASCENDING)
JohnB17
  • 25
  • 6
  • And what is your code with which you have that problem? What does latest/oldest mean? The highest/lowest number in each file basename? – hakre Jul 23 '22 at 21:44
  • Welcome to StackOverflow! We won't just do your homework for you, you have to help us. Please provide code to prove what you have tried. – ethry Jul 23 '22 at 21:44
  • what have you tried so far? where are you getting stuck? – dqhendricks Jul 23 '22 at 21:48
  • I have updated my post with what was asked, and latest/oldest means the latest file from these 2 directories. – JohnB17 Jul 23 '22 at 21:49

1 Answers1

0

I have updated this function (List all the files and folders in a Directory with PHP recursive function) to include modification time. Then sorted by it.


function getDirContents($dir, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = [
                "path" => $path,
                "mtime" => filemtime($path)
            ];
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = [
                "path" => $path,
                "mtime" => filemtime($path)
            ];
        }
    }

    usort($results, function($a, $b) {
        return $a["mtime"] <=>$b["mtime"];
    });
    return $results;
}
IT goldman
  • 14,885
  • 2
  • 14
  • 28