filter scandir and sort by date created

前端 未结 2 1249
感动是毒
感动是毒 2021-02-11 01:39
  1. I need to get the files in a directory in an array.
    • Only files that end in .markdown
  2. The files should be sorted by date created

相关标签:
2条回答
  • 2021-02-11 01:53

    You can use glob() to get an array of filenames then use usort() and filectime() to order them by their creation dates:

    $files = glob('*.markdown');
    usort($files, function($file_1, $file_2)
    {
        $file_1 = filectime($file_1);
        $file_2 = filectime($file_2);
        if($file_1 == $file_2)
        {
            return 0;
        }
        return $file_1 < $file_2 ? 1 : -1;
    });
    

    For PHP versions lower than 5.3:

    function sortByCreationTime($file_1, $file_2)
    {
        $file_1 = filectime($file_1);
        $file_2 = filectime($file_2);
        if($file_1 == $file_2)
        {
            return 0;
        }
        return $file_1 < $file_2 ? 1 : -1;
    }
    
    $files = glob('*.markdown');
    usort($files, 'sortByCreationTime');
    
    0 讨论(0)
  • 2021-02-11 02:09

    Easiest way to get the file list is simply do

    $files = glob('*.markdown');
    

    glob() basically does the same kind of wildcard matching that occurs at a shell prompt.

    Sorting by date will require you to look at each of those files with stat() and retrieve its mtime/ctime/atime values (which fileatime(), filemtime(), filectime() return directly, but still use stat() internally).

    0 讨论(0)
提交回复
热议问题