user3461829
user3461829

Reputation: 3

sort by date created php

I have a audio player and its pulling its audio from a folder its currently being sorted by name but I want to sort it by date created. any help would be appreciated.

$media = array();

    $di = new DirectoryIterator($dir);
    foreach ($di as $fileinfo) {
        $path_info = pathinfo($fileinfo->getPathname());
        if(isset($path_info['extension'])){
            if(in_array(strtolower($path_info['extension']), $allowed_files)){
                $fn = $fileinfo->getPathname();
                $media[] = array( 
                    "SITE_URL" => SITE_URL, 
                    "SITEPATH" => SITEPATH, 
                    "fullpath" => SITE_URL.'/'.path2url(realpath($path_info['dirname'])).'/'.$path_info['basename'],  
                    "basename" => $path_info['basename'], 
                    "extension" => $path_info['extension'],
                    "dirname" => realpath($path_info['dirname']),
                    "filename" => $path_info['filename']
                ); 
            }
        }

Upvotes: 0

Views: 41

Answers (1)

Nick
Nick

Reputation: 147166

DirectoryIterator only gives access to access Time, modification time or inode change time. If your files have not been changed since creation, modification time will be the same and you can then save that time in the $media array and then sort the array using array_multisort:

$media = array();

$di = new DirectoryIterator($dir);
foreach ($di as $fileinfo) {
    $path_info = pathinfo($fileinfo->getPathname());
    if(isset($path_info['extension'])){
        if(in_array(strtolower($path_info['extension']), $allowed_files)){
            $fn = $fileinfo->getPathname();
            $media[] = array( 
                "SITE_URL" => SITE_URL, 
                "SITEPATH" => SITEPATH, 
                "fullpath" => SITE_URL.'/'.path2url(realpath($path_info['dirname'])).'/'.$path_info['basename'],  
                "basename" => $path_info['basename'], 
                "extension" => $path_info['extension'],
                "dirname" => realpath($path_info['dirname']),
                "filename" => $path_info['filename'],
                "mtime" => $fileinfo->getMTime()
            ); 
        }
    }
}
array_multisort(array_column($media, 'mtime'), SORT_ASC, $media);

Upvotes: 2

Related Questions