Quote:
Originally Posted by Stephane3d
Hi,
This script works pretty well except that the files list is not ordered. I'd like to sort it alphabetically. Any idea how to do that?
For example, I got this:
0012.jpg
0011.pdf
0024.pdf
0004.jpg
0018.pdf
0008.pdf
While I'd like to get this:
0004.jpg
0008.pdf
0011.pdf
0012.jpg
0018.pdf
0024.pdf
Thanks for any help.
|
Before sorting the listed files/directories alphabetically, I coverted the function into the way listing the files/directories in list(ul/li) manner instead of the current 'intent' one. I reckon the list way is the most proper way to list nested items. Here is the new function:
PHP Code:
function getDirectory( $path = '.'){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = @opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
//Add a class as selector for the jQuery sorting later.
echo "<li>$file<ul class='has-children'>";
getDirectory( "$path/$file");
// Re-call this same function but on a new directory.
// this is what makes function recursive.
echo "</li>";
} else {
echo "<li>$file</li>";
// Just print out the filename
}
}
}
echo "</ul>";
closedir( $dh );
// Close the directory handle
}
//Add a class as selector for the jQuery sorting later.
echo "<ul class='has-children'>";
getDirectory( "." );
Then add the following jQuery codes to sort the lists:
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
$('ul.has-children').each(function() {
var $t=$(this);
var Li=$t.find('>li').get();
Li.sort(function(a, b) {
var A = $(a).text().toUpperCase();
var B = $(b).text().toUpperCase();
if (A < B) return -1; // changing to 1 to sort in DESC order...
if (A > B) return 1; // changing to -1 to sort in DESC order...
return 0;
});
$.each(Li,function(i,v) {
$t.append(v);
});
});
</script>
Have fun