boyhero Posted May 20, 2007 Share Posted May 20, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/52165-list-filenames-in-descending-numerical-order-but-also-ascending-alphabetical/ Share on other sites More sharing options...
Barand Posted May 20, 2007 Share Posted May 20, 2007 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>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/52165-list-filenames-in-descending-numerical-order-but-also-ascending-alphabetical/#findComment-257414 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.