我有点困惑,我可以如何排序我的结果。我在目录中返回一个文件列表,需要以某种方式对它们进行排序......
// 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 );
}
我将在哪里应用sort函数?
感谢
答案 0 :(得分:1)
答案是将您的条目添加到数组并对其进行排序
但是认真。你的代码(我不知道你从哪里剪掉)然而看起来真的过时了。还有更优雅的方法。
例如glob
只是为了让你的代码被修改为基本上做你想要的东西而没有任何东西你可能有以下内容:
// 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 );
}
答案 1 :(得分:0)
您需要累积每次迭代的结果,而不是将它们回显给用户。然后,在函数完成递归之后,它应该对结果进行排序。但是,仅在$level
为1时对结果进行排序。如果不这样做,它将在每次递归后对结果进行排序。
答案 2 :(得分:0)
我建议废弃该功能并使用glob
$files = glob("dir/*");
sort( $files );