Tim32 Posted October 25, 2018 Share Posted October 25, 2018 I have a folder full of documents that contain meeting minutes. Each document is named like this: Board 01-02-1977.pdf Board 01-03-1976.pdf Board 01-07-1975.pdf Board 01-09-1974.pdf Board 02-01-1978.pdf Board 02-03-1979.pdf I need to display the list sorted by y-m-d. I have it working and here is my code so far: <?php $files = array_diff(scandir('./Board'), array('..', '.', 'Default.php', 'template.php')); foreach($files as $file => $item) { $filebreak = preg_split("/(-|\.)/",$item,-1,PREG_SPLIT_NO_EMPTY); $files[$file] = $filebreak[2] . $item; } sort($files); foreach($files as $file) { $file = substr($file,4); echo "<a href='./Board/"; echo $file; echo "'>"; $file = str_replace('.php', '', $file); echo $file; echo "</a><br>"; } ?> I get an arrary of the files using scandir and get rid off the files I don't want to see. Next I take the year and append it to the beginning of the filename and then sort the array. Finally I print the results. What do you guys think? Is there a better way to do this? Did I miss something? Link to comment Share on other sites More sharing options...
Barand Posted October 25, 2018 Share Posted October 25, 2018 Firstly, I'd use glob() to get just the files I want then use a cutom sort to sort by the full date (not just year) // use glob() to get just the files you want $files = glob("./board/board*.pdf"); // custtom sort by date usort($files, function ($a, $b) { return docdate($a) <=> docdate($b); } ); foreach ($files as $f) { $base = basename($f); echo "<a href='$f'>$base</a><br>"; } /**************************************************************** * extract date portion of name and convert from m-d-Y to Y-m-d * * @param string $fn path/to/file * @returns properly formatted date *****************************************************************/ function docdate($fn) { $pi = pathinfo($fn, PATHINFO_FILENAME); $dt = DateTime::createFromFormat('m-d-Y', substr($pi, -10)); return $dt->format('Y-m-d'); } Link to comment Share on other sites More sharing options...
Tim32 Posted October 29, 2018 Author Share Posted October 29, 2018 @Barand Thank you for the ideas. I didn't know about glob. The createFromFormat is a nice way to convert the string to a date and then change the format. Thank you again, Tim Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.