Reputation: 633
im a little confused how i can sort my results. Im returning a list of files in a directory and need them to be sorted in some way...
// Start directory
getDirectory('../gallery/photos');
function getDirectory( $path = '.', $level = 0 ){
// Directories to ignore when listing output.
$ignore = array( '.', '..' );
// Open the directory to the handle $dh
$dh = @opendir( $path );
// Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ) {
// Change filename to display date
$displaydate= date('jS M Y', strtotime($file));
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) ) {
// Indent spacing for better view
$spaces = str_repeat( ' ', ( $level * 5 ) );
// Show directories only
if(is_dir( "$path/$file" ) ){
// Re-call this same function but on a new directory.
// this is what makes function recursive.
echo "$spaces<a href='$path/$file'>$displaydate</a><br />";
getDirectory( "$path/$file", ($level+1) );
}
}
}
// Close the directory handle
closedir( $dh );
}
where would i apply the sort function?
thanks
Upvotes: 0
Views: 754
Reputation: 29856
the answer would be adding your entries to an array and sort it
but seriously. your code (i dunno where you got that snipped from) however looks really outdated. there are far more elegant ways to do that.
for example glob
just to make your code modified to to essentially do what you want and nothing mroe you may have the following:
// Start directory
getDirectory('../gallery/photos');
function getDirectory( $path = '.', $level = 0 ){
// Directories to ignore when listing output.
$ignore = array( '.', '..' );
// Open the directory to the handle $dh
//$dh = @opendir( $path );
// Loop through the directory
//while( false !== ( $file = readdir( $dh ) ) ) {
$files = $files = glob($path.DS."*");
sort($files);
foreach($files as file) {
// Change filename to display date
$displaydate= date('jS M Y', strtotime($file));
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) ) {
// Indent spacing for better view
$spaces = str_repeat( ' ', ( $level * 5 ) );
// Show directories only
if(is_dir( "$path/$file" ) ){
// Re-call this same function but on a new directory.
// this is what makes function recursive.
echo "$spaces<a href='$path/$file'>$displaydate</a><br />";
getDirectory( "$path/$file", ($level+1) );
}
}
}
// Close the directory handle
closedir( $dh );
}
Upvotes: 1
Reputation: 30170
I recommend scrapping that function and using glob
$files = glob("dir/*");
sort( $files );
Upvotes: 0
Reputation: 29658
You would need to accumulate the results of each iteration, instead of echoing them to the user. Then, after the function has finished recursing, it should sort the results. Only sort the results when $level
is 1, though. If you don't, it will sort the results after every recursion.
Upvotes: 0