Jump to content

[SOLVED] grab name of file with most recent date in it


jasonc

Recommended Posts

I wish to get the file name which has the most recent date in it.

 

all files are in the following format... (dd/mm/yyy)

 

abc - 21-09-2009 - Agenda.pdf

 

but it is not getting the correct file for some reason, this is what code i am using to get the filename.

 

	$files = glob('agendas/*.pdf');
	$datestring = strtotime(basename(substr($files[0], 14, 10),".pdf"));
	$anchortext = date('j M Y',$datestring);
	// echo(".".basename(substr($files[0], 14, 10),".pdf").".");
	$url = date('dmY',$datestring);
		if (strlen(date('j',$datestring)) == 1) { ?>  <?
		} ?><strong><?=$anchortext;?></strong>

I would probably take this approach

$sortfile = array();
foreach($files as $file){
    //Extract date
    if (preg_match('/(\d+)-(\d+)-(\d+)[^.]*?\.pdf/', $file, $reg)) {
        //add date to array (file as key)
        $sortfile[$file] = mktime(0,0,0,$reg[2],$reg[1],$reg[3]);
    }
}
asort($sortfile); //Sort an array (the dates) and maintain index association (file names)

//echo files
foreach($sortfile as $file => $fdate){
   echo "$file<br>";
}

 

EDIT: updated regex and changed strtotime to mkdate

 

please note this is untested, but the last file should be the one you want, or use arsort and it will be the first one :P

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.