Sorting folders in PHP

Hi - I’m modifying some PHP code that someone else wrote. Below is a snippet of code that basically takes mp3 files files within all the folders in a directory, and creates an RSS feed. In the resulting feed, the files are intermingled in date order.

Instead, I’d like them sorted by the directory that they are in. So, if there are files in these directories:


I’d like all the files in the “01-First” directory to come before the “02-Second” directory and so on. Within each directory the files can be sorted as they currently are (I don’t see a sort specified below, so I assume the default is by date, oldest to newest which is fine). How would I go about doing that? Thanks.

$VMHome = $SpoolRoot.$context.'/';
if ($url_params['mode'] == 'rss2') {
	print getRSSHeader('UTF-8', $device, $vm_config, $vm_name, $web_master, $logo_image,$context);
    $mailboxes = array();
	if ($dev_dir = @opendir($VMHome . $device)) { //might fail if mailbox has not received first message yet
		while ($f = readdir($dev_dir)) {
	    	if (!eregi("tmp","$f") && !eregi("\.+","$f") && !eregi("Exclude-From-CD", "$f")) { //skip tmp directory and Exclude-From-CD Directories		  
    			array_push($mailboxes,"$f"); #collect all existing mailboxes
		foreach ($mailboxes as $mailbox) {
			$dir_name = $VMHome . $device . '/'. $mailbox .'/'; 
			$dir = opendir($dir_name);
			while ($f = readdir($dir)) {
 				if (eregi("\.txt",$f)){ #if filename matches .txt in the name
    				array_push($files,"$f"); #push into $files array
			foreach($files as $file){
  				$props = getProperties($dir_name, $file);
	  			$uid = getMP3File($dir_name, $file, $props, $device, $mailbox, $vm_config, $vm_name,$context);
  				print getRSSItem ($props, $uid, $dir_name, $device, '/' . $mailbox . '/', $context);      
	print	 '

I don’t know PHP so I can’t answer your question specifically, but you wouldn’t be sorting folders you would be sorting an array. PHP gets the folder names one at a time and puts them into the array $mailboxes, and for each file it finds in $mailboxes does another loop to put the files into an array called $files.

You might want to google “sorting an array in PHP” to help.

I think if you add this line just before the foreach ($mailboxes …) loop it will do what you want:

sort ($mailbox);

The sort() function has a SORT_NUMERIC option that might be of interest.

Don’t assume opendir/readdir will sort by date - the order is undefined. If you need it sorted by date, make sure it is.

There’s a sort function that allows you to take in a callback function - the usort function. In your case, the function will compare the timestamp of the directory, which I believe you can get using the filemtime function.

Thanks everyone for your advice! I was able to piece together some code that does the trick. Thanks, again.