0

I have a bunch of files on my server with file names from 'april2009' to 'march2013', a file for every month in between (plus a new file for every month from now onwards will be added).

I tried arranging in order by using 'filemtime', but this gave a random order as they appear to have been modified all over the place.

How can I sort through the file names and arrange in order, starting at most recent first?

(getting the file names with php, but can use jquery or a mix for this purpose)

thanks

rpsep2
  • 3,061
  • 10
  • 39
  • 52
  • The obvious solution is: Change the filenames to be yyyy-mm-dd instead of your current format and then sort by name. But I guess that's out of the question? – Till Helge Mar 11 '13 at 12:46
  • Check the accepted answer here. Is just what you need. http://stackoverflow.com/questions/124958/glob-sort-by-date – Ateszki Mar 11 '13 at 12:46
  • it is yes, the filenames are set like this as they are being used in multiple other places which code would need to be changed for as well – rpsep2 Mar 11 '13 at 12:46
  • @Ateszki Please read the question properly. The OP clearly states that sorting by modification time doesn't work. – Till Helge Mar 11 '13 at 12:47
  • @Till Helge Helwig sorry, you are right! I missed the part that the files have modified after creation. – Ateszki Mar 11 '13 at 12:50

2 Answers2

1

strtotime is amazing for date conversion.

Once you have retrieve your file list, you can do:

$date = strtotime('april2003');

Which will give you: 1049155200. Which means:

1/4/2003 à 2:00:00

Once you have your timestamp, you can do what ever you want to sort it.

Here is a POC:

$dirs = array();
if ($handle = opendir('/path/to/dir')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != ".." && is_dir($entry)) {
            $dirs[strtotime(substr($entry, 0, -5))] = $entry;
        }
    }
    closedir($handle);
}

krsort($dirs);
j0k
  • 22,600
  • 28
  • 79
  • 90
  • Thanks for this. Im struggling with something though: the directory files have a .html extension, which i think is messing up the strtotime. i was getting around this using 'substr($file, 0 , -5);', but in unsure how to implement this into the above code? – rpsep2 Mar 11 '13 at 13:11
0

To put it mildly, this should have been thought about before coming up with the file namning convention. As pointed out in the comments, the only sensible naming convention is a sortable one yyyy-mm or yyyy-mm-dd.

In this case your only option is to:

  1. Load the list of file names
  2. While loading them, convert the names to a sortable form (so you would transform april2003 to 200304)
  3. As you load them place them in an array of the form $img[$sortablefilename] = $real file name (e.g. $img['200304'] = 'april2003';)
  4. Use ksort to sort the resulting array
  5. Read through the sorted array using the real file names to display the images
Captain Payalytic
  • 1,061
  • 8
  • 9