Page 1 of 1

Sorting number reversed problem...

Posted: Wed Jan 21, 2009 11:49 am
by Peuplarchie
Good day top you all,
I'm working on a script that read a folder a list directory.
The files in that folder are named by number, like 0 to 200.

here how it would look like :

003
002
001
010
...

How can I make my list in complete reverse order like :

010
...
003
002
001


here is my code :

Code: Select all

 
function listFilesInDir($start_dir)
 
        {
        
        /*
        returns an array of files in $start_dir (not recursive)
        */
                
        $files = array();
        $dir = opendir($start_dir);
$count =0;
        while(($myfile = readdir($dir)) !== false)
                {
                if($myfile != '.' && $myfile != '..' && !is_file($myfile) && $myfile != 'resource.frk' && !eregi('^Icon',$myfile) )
                        {
                        $count = $count +1; 
                        $files[] = $myfile;
                        }
                }
        closedir($dir);
        rsort($files);
        return $files;
        
 
        }
 
Thanks !

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 12:12 pm
by Burrito
what you have should do it.

rsort() will sort the the array in descending order. Keep in mind though that strings sort differently than integers.

ex: 10.php would be before 9.php.

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 12:28 pm
by Peuplarchie
how can I fix this...

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 12:33 pm
by Burrito
my suggestion would be to split the filename from its extension and run it through intval() to parse the names as ints then use that as the key for the array.

you can then use krsort() to sort it by key and extract the values from the array from there.

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 12:37 pm
by Peuplarchie
sounds great, looking around to see how could I code that....

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 2:05 pm
by Peuplarchie
Solved !

Code: Select all

 
natsort($files);
$files = array_reverse($files);  
 

Re: Sorting number reversed problem...

Posted: Wed Jan 21, 2009 2:13 pm
by Burrito
very nice. didn't know about natsort()...I like it :)