Jump to content

List filenames in descending numerical order, but also ascending alphabetical


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>';
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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