Problem in Sorting Files by date modified in php

one text

Solution:

You need to update getNodes() to add the file modification time to the result set. You're currently only populating the entries' names, and as you are right in saying, scandir() can sort only on the filename. What you need is an extra call to retrieve the stat (meta) information for each entry, and store that alongside the name.

You can update getNodes() like so:

private function getNodes($directory = null)
{
    $folders = [];
    $files = [];

    $nodes = scandir($directory);

    foreach ($nodes as $node){

        if (!$this->exclude($node)) {
            $entry = [ 'name' => $node, 'mtime' => filemtime("$directory/$node") ];
            if (is_dir($directory.'/'.$node)) {
                $folders[] = $entry;
            } else {
                $files[] = $entry;
            }
        }
    }

    $entries = array_merge($folders, $files);
    usort(
        $entries,
        function ($a, $b) { return $a['mtime'] < $b['mtime']; }
    );

    return $entries;
}

And update createStructure() as follows:

private function createStructure($directory, $root)
{

    $structure = $root ? '<br><div><h1>' : '<div>';

    $nodes = $this->getNodes($directory);

    foreach ($nodes as $node) {
        $path = $directory.'/'.$node['name'];
        if (is_dir($path) ) {
            $structure .= '<div id="body">';
            $structure .= ''.$node['name'].'';
            $structure .= self::createStructure($path, false);
            $structure .= '</div><br>';
        } else {
            $path = str_replace($this->root.'/', null, $path);

            $structure .= '<a href="activities/'.$path.'">
                           <img src="activities/'.$path.'" width="250px" height="200px" >
                           </a>';

        }
    }

    return $structure.'</div>';
}

Source