Jump to content

Directory traverse/sorting problem


nucleardreamer

Recommended Posts

Hi guys, I seem to be having a problem with this function that spits out directories. There is a numeric prefix that is on every directory, so it automatically sorts these by the numbers, not the name of the actual folder I want to display. So to sort correctly I did the following (and I know it works right because the array is the same but sorted different) but every time I do it, it gives me a 500 error, I dont know whats causing it!

 

One thing that is possibly (or more likely) is that the directory names are somehow different, there is a space somewhere i don't know... something?!

 

//example foldername: -20090101N-TestFolder
// I want it to sort by TestFolder not the starting date of the name.

function traverseDirTree($base,$fileFunc,$dirFunc=null,$afterDirFunc=null){
        // this is the spot where the prefix ends
        $scan_index=11;
        // puts the dir from $base into an array
        $subdirectories = scandir($base);

     // breaks the array apart, putting the original prefix at the end, and stores a temp array
 foreach($subdirectories as $myscan){
	if ($myscan != "." && $myscan != "..") {
		$newScan = substr($myscan,$scan_index).substr($myscan,0,$scan_index);
		$scan_temp[]=$newScan;
	}
}
// sort the temp dir, and empty the original array
sort($scan_temp);
$subdirectories = array();

// put the prefix back in the beginning after its sorted
foreach($scan_temp as $scan){
    $newScan = substr($scan,(0-$scan_index),$scan_index).substr($scan,0,(0-$scan_index));
    $subdirectories[]=$newScan;
}

// this traverses the directory, looking for files and subdirectories, then running the script again for every subdir
foreach ($subdirectories as $subdirectory){
if ($subdirectory != "." && $subdirectory != "..") {
	$path=$base.$subdirectory;
	if (is_file($path)){
	  if ($fileFunc!==null) $fileFunc($path);
	}else{
	  if ($dirFunc!==null) $dirFunc($path);
	  if (($subdirectory!='.') && ($subdirectory!='..')){
		traverseDirTree($path.'/',$fileFunc,$dirFunc,$afterDirFunc);
	  }
	  if ($afterDirFunc!==null) $afterDirFunc($path);
	}
    }
  }
}

Link to comment
https://forums.phpfreaks.com/topic/146572-directory-traversesorting-problem/
Share on other sites

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.