开发者

Separating output by line alphabetically

I have the code below that outputs the names of files in a directory. I'd like to separate the file names alphabetically by an additional line space when the first letter of the file changes (say from A to B). Any ideas? Thanks.

            $dirs = scandir("Dir");
            foreach($dirs as $file)
            {
                    if (($file == '.')||($file == '..'))
                    {
                    }
                    elseif (is_dir($tdir.'/'.$file))
                    {
                            filesInDir($tdir.'/'.$file);
          开发者_如何学JAVA          }
                    else
                    {
                            echo $file."<br>";
                    }
            }


You can just monitor the first character of each file name. You can access individual characters of a string using array syntax, such as $string[0] for the first character:

        $dirs = scandir("Dir");
        $char = null;
        foreach($dirs as $file)
        {
                if (($file == '.')||($file == '..'))
                {
                }
                elseif (is_dir($tdir.'/'.$file))
                {
                        filesInDir($tdir.'/'.$file);
                }
                else
                {
                        if ($file[0] != $char && $char !== null) echo "<br>";
                        echo $file."<br>";
                        $char = $file[0];
                }
        }


You can solve this by storing the previous file name at the end of the loop, and then compare its first character with the current file's first one by using strncasecmp. If the return value != 0, then the characters are different; thus, an extra BR tag is added.


            $dirs = scandir("Dir");
            foreach($dirs as $file)
            {
                    if (($file == '.')||($file == '..'))
                    {
                    }
                    elseif (is_dir($tdir.'/'.$file))
                    {
                            filesInDir($tdir.'/'.$file);
                    }
                    else
                    {
                            echo $file."<br>";
                            if (strncasecmp($file, $previousFile, 1)) echo "<br>";
                    }
                    $previousFile = $file;
            }


Kind of a hack, BUT if your on *nix:

ls -al |  awk '{print $9}'

Will give you back the directories contents in alphabetical order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜