need help sorting list of files
Posted: Wed Jan 05, 2011 10:09 am
Hi,
I'm new to PHP, but have used Javascript quite a bit before. I wanted to create a script that retrieves filenames from a folder on my webserver, then reverse sorts those files and makes them into clickable links. After some searching on Google, I decided PHP was the way to go, and so I wrote the following script. The filenames are in the format "Entos_Web_MM-DD-YY.pdf", and I use the substr command to shorten the text of the links to just "MM-DD-YY". The problem I'm having is that this only sorts based on month first, then day, then year (as would be expected since that is the order the characters are in). However, I'd like it to sort it on year first, so that the ones from January 2011 come before December 2010 files. I'm sure there's a way to do this by using the substr command to get only the "YY" portion of the filename and sort based on that, but I'm struggling with how exactly to do that and put it back into the array.
Here is the script:
I'm new to PHP, but have used Javascript quite a bit before. I wanted to create a script that retrieves filenames from a folder on my webserver, then reverse sorts those files and makes them into clickable links. After some searching on Google, I decided PHP was the way to go, and so I wrote the following script. The filenames are in the format "Entos_Web_MM-DD-YY.pdf", and I use the substr command to shorten the text of the links to just "MM-DD-YY". The problem I'm having is that this only sorts based on month first, then day, then year (as would be expected since that is the order the characters are in). However, I'd like it to sort it on year first, so that the ones from January 2011 come before December 2010 files. I'm sure there's a way to do this by using the substr command to get only the "YY" portion of the filename and sort based on that, but I'm struggling with how exactly to do that and put it back into the array.
Here is the script:
Code: Select all
<?php
if ($handle = opendir('newsletter')) {
$filenames = array();
$filenames2 = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$filenames[] = $file;
}
rsort($filenames);
}
closedir($handle);
}
$i = 0;
while ($i <= count($filenames)) {
$thelist .= '<a target="_blank" href="newsletter/'.$filenames[$i].'">'.substr($filenames[$i],10,-4).'</a><br>';
$i++;
}
$thelist2 = implode($filenames);
?>
<head>
<style type="text/css">
body
{
background-color: #999966;
overflow: auto;
}
A:link {text-decoration: none; color: blue; outline:none}
A:visited {text-decoration: none; color: blue; outline:none}
A:active {text-decoration: none; color: blue; outline:none}
A:hover {color: red; text-decoration: none; outline:none}
</style>
</head>
<body>
<img src="images/entos.jpg" style="width:100px;">
<br>
Newsletter Archive
<br>
<br>
<P><?=$thelist?></p>
</body>