Maria Jeysingh Anbu
Maria Jeysingh Anbu

Reputation: 3312

PHP get foldername sort by created date

I want get all the foldernames inside the directory and sort by the created date. now I am using the following code for getting all the fodernames inside the directory.

$path = 'userfiles';
$dirs = array();
// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry;

       }
    }
}

It displays all the foldername but not by created date.

Userfiles
-->My Folder
-->My Folder 2

Upvotes: 3

Views: 209

Answers (2)

mickmackusa
mickmackusa

Reputation: 47883

Access the subdirectories by calling glob() with a path parameter of Userfiles/* and the GLOB_ONLYDIR flag.

Then call usort() and sort the directories in ASC order. *if you want them in DESC order, just switch function parameters to $b,$a.

$directories=glob('Userfiles/*',GLOB_ONLYDIR);
usort($directories, function($a,$b){ return filemtime($a) - filemtime($b); });
var_export($directories);

Also, if your current working directory (where your script is located) is in "Userfiles", then you will only need this: glob('*',GLOB_ONLYDIR) and the output will be e.g.:

array ( 0 => 'My Folder', 1 => 'My Folder 2', )

If you are not in your CWD, then call chdir() to move before calling glob().

p.s. from PHP7.4 and up, you can use arrow function syntax:

usort($directories, fn($a, $b) => filemtime($a) <=> filemtime($b));  // sort ASC

Upvotes: 3

Sphiwe Molala
Sphiwe Molala

Reputation: 11

I've modified your code a little, the method below takes advantage of array keys and eliminates the need to create objects or multi-dimensional array to contain additional data.

Here, we get the last modified date as an integer and use that as a key for each entry/folder name, then sort the array using the keys, I've added some comments for clarity.

$path = 'absolute/path/to/folder';
$dirs = array();
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
        $fullpath = $path . $entry;

        $time = @filemtime($fullpath);//This will fail on systems not using ISO-8859-1 for encoding
        if(!$time)//if NULL
            $time = filemtime(utf8_decode($fullpath));//Convert encoding to ISO-8859-1

        if ( is_dir($fullpath) )
            $dirs[$time] = $entry;//Use last modified time as key to this array
    }
}
//Then just sort by keys below
ksort($dirs);//from old to new
krsort($dirs);//from new to old

You can then just use the key to show the user dates next to the folder names

Upvotes: 0

Related Questions