NYCPHP Meetup

NYPHP.org

[nycphp-talk] Listing files... alphabetically

Adam Maccabee Trachtenberg adam at trachtenberg.com
Wed Nov 26 01:54:02 EST 2003


On Tue, 25 Nov 2003, Robert Dumas wrote:

> I really appreciate the help. Hooo, boy, am I close now.
>
> Here's the current code. It seems to work, with only two problems:
> 1) it outputs all the filenames under the FIRST bullet point.
> 2) likely related to #1. the links do not point to the proper subfolders.

Your problem is that your code collects all thee subfolder files but
doesn't track their parent folder. So, when you natsort() them
everything gets mix up.

The easiest way to solve this problem is with recursion. When you use
recursion, you call a function from *within* that function. (If you've
never done this before, it can be a bit of a mind twister.) In this
case, your code to print a subfolder is practically identical to the
code to print its parent. Whenever you notice this self-similarity,
it's a good sign you want to use recursion.

Here's a rewritten version that does the same thing that you were
trying to do:

function dirlist($path, $level) {
  if (is_dir($path)) {
    $files = array();
    $handle = opendir($path);

    while ( false !== ($file = readdir($handle)) ) {
      if ( ($file!='.') && ($file!='..') && ($file!='index.php') ) {
        $files[] = $file;
      }
    }

    closedir($handle);
    natsort($files);

    echo "<ul>\n";
    while (list ($key, $val) = each($files)) {
      if ($level) {
        $val = "<a href=\"$path/$val\">$val</a>";
      }
      echo "<li>$val</li>\n";
      dirlist("$path$val", $level + 1);
    }
    echo "</ul>\n";
  }
}

dirlist('/path/to/songs.mp3', 0);

If you look at the code, you see that I iterate through a directory
and gather up all the files. Then I sort them. Last, I print
them, but after I print each item, I call dirlist() again!

If it's not a directory, nothing happens. If it is, then I repeat the
whole process inline.

Since you print <li>s differently if they're in a subfolder instead of
the top level, I needed to use a $level variable to track where you
are and add the <a> tag around $val. Also, I used $path as the prefix,
but this isn't really right. You'll probably want to modify
this. That's left as an exercise for the programmer.

-adam

-- 
adam at trachtenberg.com
author of o'reilly's php cookbook
avoid the holiday rush, buy your copy today!



More information about the talk mailing list