filter scandir and sort by date created

前端 未结 2 1248
感动是毒
感动是毒 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');
    

提交回复
热议问题