PHP读取目录排序?

时间:2012-01-18 22:03:37

标签: php

我有:

$directory='testdirectory/';
$handler = opendir($directory);
while ($file = readdir($handler)) {
...
}

这样排序的opendir / readdir的输出是什么?是日期,字母还是别的,因为我无法从输出中看出来。

2 个答案:

答案 0 :(得分:4)

http://php.net/readdir说:“条目按文件系统存储的顺序返回。”

答案 1 :(得分:2)

如前所述,很难控制readdir()列出文件的顺序。此函数可以帮助您 - 它获取目录的路径,在关联数组中创建它们的列表,并根据名称,大小或访问/修改/创建的时间对它们进行排序。希望它的用法应该是相当自我解释的。

// Constants to make usage more reader-friendly
define('DIR_SORT_NAME',  1);
define('DIR_SORT_SIZE',  2);
define('DIR_SORT_ATIME', 3);
define('DIR_SORT_MTIME', 4);
define('DIR_SORT_CTIME', 5);

function readdir_sorted_array ($dir, $sortCol = DIR_SORT_NAME, $sortDir = SORT_ASC) {

  // Validate arguments
  $dir = rtrim(str_replace('\\', '/', $dir), '/');
  $sortCol = (int) ($sortCol >= 1 && $sortCol <= 5) ? $sortCol : 1;
  $sortDir = ($sortDir == SORT_ASC) ? SORT_ASC : SORT_DESC;
  $name = $size = $aTime = $mTime = $cTime = $table = array();

  // Open the directory, return FALSE if we can't
  if (!is_dir($dir) || (!$dp = opendir($dir))) return FALSE;

  // Fetch a list of files in the directory and get stats
  for ($i = 0; ($file = readdir($dp)) !== FALSE; $i++) {
    if (!in_array($file, array('.','..'))) {
      $path = "$dir/$file";
      $row = array('name'=>$file,'size'=>filesize($path),'atime'=>fileatime($path),'mtime'=>filemtime($path),'ctime'=>filectime($path));
      $name[$i] = $row['name'];
      $size[$i] = $row['size'];
      $aTime[$i] = $row['atime'];
      $mTime[$i] = $row['mtime'];
      $cTime[$i] = $row['ctime'];
      $table[$i] = $row;
    }
  }

  // Sort the results
  switch ($sortCol) {
    case DIR_SORT_NAME:
      array_multisort($name, $sortDir, $table);
      break;
    case DIR_SORT_SIZE:
      array_multisort($size, $sortDir, $name, SORT_ASC, $table);
      break;
    case DIR_SORT_ATIME:
      array_multisort($aTime, $sortDir, $name, SORT_ASC, $table);
      break;
    case DIR_SORT_MTIME:
      array_multisort($mTime, $sortDir, $name, SORT_ASC, $table);
      break;
    case DIR_SORT_CTIME:
      array_multisort($cTime, $sortDir, $name, SORT_ASC, $table);
      break;
  }

  // Return the result
  return $table;

}