按时间排序文件夹php

时间:2012-11-19 12:37:40

标签: php subdirectory dir

此代码显示文件夹列表。

如何按时间(最后更改)对这些文件夹进行排序?     

function folderlist(){
  $startdir = './';
  $ignoredDirectory[] = '.'; 
  $ignoredDirectory[] = '..';
   if (is_dir($startdir)){
       if ($dh = opendir($startdir)){
           while (($folder = readdir($dh)) !== false){
               if (!(array_search($folder,$ignoredDirectory) > -1)){
                 if (filetype($startdir . $folder) == "dir"){
                       $directorylist[$startdir . $folder]['name'] = $folder;
                       $directorylist[$startdir . $folder]['path'] = $startdir;
                   }
               }
           }
           closedir($dh);
       }
   }
return($directorylist);
}

$folders = folderlist();
    foreach ($folders as $folder){
    $path = $folder['path'];
    $name = $folder['name'];

echo '<li><a href="' .$path .'index.php?imgdir=' .$name . '" class="style1"><font face="Tahoma" class="ws8"><B>' . $name . '</B></a><br /></li>';
  }
?>

1 个答案:

答案 0 :(得分:2)

您必须在filemtime()中加入$directoryList[],然后按照mtime对数组进行排序。

function cmp_mtime_reverse($a, $b) {
    if ($a['mtime'] == $b['mtime'])
        return 0;

    if ($a['mtime'] > $b['mtime'])
        return -1;

    return 1;
}

function folderlist() {
    $startdir = './';
    $ignoredDirectory[] = '.'; 
    $ignoredDirectory[] = '..';
    if (is_dir($startdir)) {
        if ($dh = opendir($startdir)) {
            while (($folder = readdir($dh)) !== false) {
                if (!(array_search($folder,$ignoredDirectory) > -1)) {
                    if (filetype($startdir . $folder) == "dir") {
                        $mtime = filemtime($startdir . $folder);
                        $directorylist[$startdir . $folder]['name'] = $folder;
                        $directorylist[$startdir . $folder]['path'] = $startdir;
                        $directorylist[$startdir . $folder]['mtime'] = $mtime;
                        $directorylist[$startdir . $folder]['files'] = count_files($startdir . $folder);
                    }
                }
            }

            closedir($dh);
        }
    }

    uasort($directorylist, 'cmp_mtime_reverse');
    return $directorylist;
}

有关详细信息,请参阅Sorting Arraysfilemtime

计算文件夹中的文件

function count_files($startdir) {
    $ignoredDirectory[] = '.'; 
    $ignoredDirectory[] = '..';
    $n = 0;
    if ($dh = opendir($startdir)) {
        while (($file = readdir($dh)) !== false) {
            if (!(array_search($file, $ignoredDirectory) > -1)) {
                $n++;
            }
        }

        closedir($dh);
    }

    return $n++;
}

然后在函数folderlist()

中添加一个条目
$directorylist[$startdir . $folder]['files'] = count_files($startdir . $folder);