2010-11-14 40 views
0

列出的文件我有点困惑如何我可以排序我的结果。我返回一个目录中的文件列表,并需要他们以某种方式排序...我如何排序由php

// 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); 
} 

我在哪里应用排序功能?

感谢

+0

之前,每个人都建议使用'水珠()'现在,请阅读[Bill Karwin](http://stackoverflow.com/users/20860/bill-karwin)的[将球体测试](http://www.phparch.com/2010/04/28/putting -glob-to-the-test) – Gordon 2010-11-14 23:29:20

回答

0

我建议废弃该功能,并使用glob

$files = glob("dir/*"); 
sort($files); 
+1

他有多个层次。 – 2010-11-14 23:23:50

+0

glob()应该自动为你排序列表,至少这是它的默认行为 – 2010-11-14 23:24:20

+0

,我不知道他想要什么样的排序,所以我jsut显示排序会去哪里。 – Galen 2010-11-14 23:27:02

0

你会需要积累,而不是他们呼应给用户的每个迭代的结果。然后,在函数完成递归之后,它应该对结果进行排序。不过,只有当$level为1时才对结果进行排序。如果你不这样做,它会在每次递归之后对结果进行排序。

1

答案是加入您的输入到一个数组和排序它

但严重。你的代码(我不知道你从哪里得到的),但看起来确实过时了。有更好的方法来做到这一点。

例如glob

只是为了让你的代码修改,基本上你想要什么,没有什么MROE你可能有以下几点:

// 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('&nbsp;', ($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); 
} 
+0

感谢您的帮助乔,我有一些麻烦得到这个工作:解析错误:语法错误,意外的')',期待在J:\ xampp \ htdocs \ bunker \ test \ gallery.php T_PAAMAYIM_NEKUDOTAYIM 33行...第33行是 - foreach($ files as file){ – alsweet 2010-11-14 23:51:20