Jump to content

List filenames in descending numerical order, but also ascending alphabetical


boyhero

Recommended Posts

Hello,

 

I am trying to write a script that lists the filenames in a directory in descending numerical order, followed by ascending alphabetical order.

 

For example, I have the following filenames in a directory:

 

20070317_Pear.jpg
20070421_Kiwi.jpg
20070423_Grape.jpg
20070519_Apple.jpg
20070519_Banana.jpg
20070519_Orange.jpg

 

My desired list order is:

 

20070519_Apple.jpg
20070519_Banana.jpg
20070519_Orange.jpg
20070423_Grape.jpg
20070421_Kiwi.jpg
20070317_Pear.jpg

 

So, within a group of files that begin with the same number, I'd like the files to sort in ascending order by alphabet, rather than descending order.

 

Here's the code I've attempted. It sorts numerical in descending order, but won't sort alphabetically in ascending order:

 

   <?php
   $path = $_SERVER[DOCUMENT_ROOT]."/projecttemplate/";
   $dh = @opendir($path);

   $files = array();

   while (false !== ($file = readdir($dh))) {
			array_push($files, $file);
		}

   rsort($files);
   
   foreach ($files as $file){
	echo($file)."<br />";
   }

?>

 

The result is this:

20070519_Orange.jpg
20070519_Banana.jpg
20070519_Apple.jpg
20070423_Grape.jpg
20070421_Kiwi.jpg
20070317_Pear.jpg

 

Any ideas what I'm doing wrong?

 

Sorry, if this is a simple problem. I'm still quite a newbie.

 

Thanks in advance.

try using a custom sort function

<?php
function filesort($a, $b)
{
    list ($anum, $aalph) = explode ('_', $a);
    list ($bnum, $balph) = explode ('_', $b);
    
    if ($anum == $bnum) return strcmp($aalph, $balph);
    return $anum > $bnum ? -1 : 1;
}

$files = array (
    '20070519_Apple.jpg',
    '20070423_Grape.jpg',
    '20070317_Pear.jpg',
    '20070519_Banana.jpg',
    '20070421_Kiwi.jpg',
    '20070519_Orange.jpg'
) ;

usort ($files, 'filesort');        // call custom sort function

/**
* check result
*/

echo '<pre>', print_r($files, true), '</pre>';
?>

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.