du512053619 2014-05-04 17:37
浏览 86

排序文件夹类型或按字母排序时出现问题

I had some issues while trying to sort my opendir. The code is basic opendir and is set to display a urls directory. I was trying to sort the output as either folder type or by alphabet but I had no luck. Here is the code:

 <?
 $dir = "../";
 if (is_dir($dir)){
 if ($dh = opendir($dir)){
 while (($file = readdir($dh)) !== false){
 echo "<a href=''>".$file."<a><br>";
 }
 } 
 }
 ?>

How can I sort my $file as either alphabet or folder type?

  • 写回答

2条回答 默认 最新

  • dousunle5801 2014-05-04 17:56
    关注

    You might start with something like the following script. I've added comments to explain it.

    For sorting things, change the while-loop to not output directly, but to store dir or file in an array by type. Then return that array, let's name it dircontent. Then apply your sort() function to dircontent. Then foreach over dircontent to output the sorted files and folders (you saved the type before, so you know again, if its file or folder).

    If you want this to go deeper in the hierarchie, put a showDir($dir) inside the is_dir() check.

    <?php
    
    /**
     * List the folders of a dir and show only PHP files.
     */
    function showDir($dir)
    {   
        $handle = opendir($dir);
    
        while ($dir = readdir($handle)) {
            // exclude dot files/folders
            if ($dir === '.' or $dir === '..') {
                continue;
            }
    
            // is this a dir?
            if(is_dir($dir)) {
                echo '<a href=' . $dir . '>' . $dir . '<a><br>';
            }
    
            // is it a file?
            if(is_file($dir)) {
    
                // get file extension, in order to check if it's a PHP file
                $ext = pathinfo($dir, PATHINFO_EXTENSION);
    
                // is it a PHP file?
                if($ext === 'php') {
                    // indent files a bit
                    echo '|-  ' . $dir . '<br>';
                }
            }
        }
    
        closedir($handle);
    }
    
    showDir(".");
    
    ?>
    

    Keep in mind, that there are other solutions around: to name a few scandir(), glob() or DirectoryIterator(). The opendir()/readdir()/closedir() approach is a bit rusty, but works.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制