0

如何按时间排序文件夹示例我在目录中创建最后一个/最新文件夹,因此最后一个文件夹显示在顶部。

这是仅显示目录的代码

<?php

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?album=' .$name . '" class="style1"><font face="Tahoma" class="ws10"><B>' . $name . '</B></a><br /></li>';
  }
?>
4

1 回答 1

1

为此,您需要首先获取文件夹的创建时间,并将其添加为数组项的键的开始,然后您将能够根据键进行排序......像这样

<?php
function folderlist(){
  $directorylist = array();
  $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"){
                       $created = filectime($startdir . $folder);
                       $directorylist[$created . $startdir . $folder]['name'] = $folder;
                       $directorylist[$created . $startdir . $folder]['path'] = $startdir;
                   }
               }
           }
           closedir($dh);
       }
   }

  ksort($directorylist);
  return($directorylist);
}


$folders = folderlist();

$total_files = 0;
foreach ($folders as $folder){
    $path = $folder['path'];
    $name = $folder['name'];
    $count = iterator_count(new DirectoryIterator($path . $name));
    $total_files += $count;

    echo '<li>';
    echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
    echo '<strong>' . $name . '</strong>';
    echo ' (' . $count . ' files found)';
    echo '</a>';
    echo '</li>';
}
  echo "Total Files:". $total_files;
?>

请注意正在使用的新 $created 变量,以及用于按其键对数组进行排序的 ksort() 方法。

您可以使用 krsort 以相反的顺序进行排序。

您还可以使用 filemtime() 而不是 filectime() 将排序更改为基于修改的日期

于 2012-11-18T07:52:32.383 回答