scandir() to sort by date modified

匿名 (未验证) 提交于 2019-12-03 02:18:01

问题:

I'm trying to make scandir(); function go beyond its written limits, I need more than the alpha sorting it currently supports. I need to sort the scandir(); results to be sorted by modification date.

I've tried a few solutions I found here and some other solutions from different websites, but none worked for me, so I think it's reasonable for me to post here.

What I've tried so far is this:

function scan_dir($dir) {     $files_array = scandir($dir);     $img_array   = array();     $img_dsort   = array();     $final_array = array();      foreach($files_array as $file)     {         if(($file != ".") && ($file != "..") && ($file != ".svn") && ($file != ".htaccess"))         {             $img_array[] = $file;             $img_dsort[] = filemtime($dir . '/' . $file);            }     }      $merge_arrays = array_combine($img_dsort, $img_array);     krsort($merge_arrays);      foreach($merge_arrays as $key => $value)     {         $final_array[] = $value;         }      return (is_array($final_array)) ? $final_array : false; } 

But, this doesn't seem to work for me, it returns 3 results only, but it should return 16 results, because there are 16 images in the folder.

回答1:

function scan_dir($dir) {     $ignored = array('.', '..', '.svn', '.htaccess');      $files = array();         foreach (scandir($dir) as $file) {         if (in_array($file, $ignored)) continue;         $files[$file] = filemtime($dir . '/' . $file);     }      arsort($files);     $files = array_keys($files);      return ($files) ? $files : false; } 


回答2:

I think the issue in your original code is multiple files could have same modification date/time hence when combining the arrays multiple file entries with same modification date/time will get overwritten and you will only get only one entry in the final array for that timestamp.



回答3:

Alternative example..

$dir = "/home/novayear/public_html/backups"; chdir($dir); array_multisort(array_map('filemtime', ($files = glob("*.{sql,php,7z}", GLOB_BRACE))), SORT_DESC, $files); foreach($files as $filename) {   echo "".substr($filename, 0, -4)."
"; }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!