Jump to content

sort filenames y-m-d when it contains m-d-y


Tim32
 Share

Recommended Posts

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

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

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.