从文件夹中排序文件

时间:2014-03-31 05:32:11

标签: php sorting

我使用以下php代码从文件夹logfiles_patient

获取所有文件
$path = "logfiles_patient/";
    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");
    // Loop through the files
    while ($file = readdir($dir_handle)) 
    {
        if(($file!='.')&&($file!='..'))
        {
    echo "<a target='_blank' href='log_Patient_download.php?filename=$file'>$file</a>";
        }
    }
    // Close
    closedir($dir_handle);

并且回显的输出是

March 19, 2014.txt
March 20, 2014.txt
March 21, 2014.txt

我想将输出重新排列为

March 21, 2014.txt
March 20, 2014.txt
March 19, 2014.txt

2 个答案:

答案 0 :(得分:3)

我建议你尝试这样的事情:

$files = glob('logfiles_patient/*');
if(is_array($files)){
    foreach ($files as $file){
        $coll[basename($file)] = filemtime($file);
    }
    asort($coll);
    $files = array_keys($coll);
}

请注意,如果glob()遇到错误,则会返回false

答案 1 :(得分:1)

您可以暂时将$file var存储在array中,并在while循环后应用sorting functions

像这样:

$array = array();    

while ($file = readdir($dir_handle))
{
     if(($file!='.')&&($file!='..'))
          $array[] = $file;
}

$array = arsort($array);

foreach($array as $file)
    echo "<a target='_blank' href='log_Patient_download.php?filename=$file'>$file</a>";