Get most recent files recursively with PHP

前端 未结 4 1778
独厮守ぢ
独厮守ぢ 2021-01-24 04:54

I am looking for code which lists the five most recent files in a directory recursively.

This is non-recursive code, and would be perfect for me if it was recursive:

4条回答
  •  渐次进展
    2021-01-24 05:31

    Edit : Sorry I didn't see the part "recursively".

    To get RECENTS files first (html for example), please sort like this with anonymous function :

    $myarray = glob("*.*.html");
    usort($myarray, function($a,$b){
      return filemtime($b) - filemtime($a);
    });
    

    And to get it recursively you can :

    function glob_recursive($pattern, $flags = 0) {
        $files = glob($pattern, $flags);
        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }
        return $files;
    }
    

    So, replace then the glob function by :

    $myarray = glob_recursive("*.*.html");
    usort($myarray, function($a,$b){
      return filemtime($b) - filemtime($a);
    });
    

提交回复
热议问题