note 53322 deleted from control-structures.foreach by felipe
| From: | felipe@php.net | Date: | Tue, 29 Jan 2008 11:24:55 +0000 |
| Subject: | note 53322 deleted from control-structures.foreach by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-135526@lists.php.net to get a copy of this message | ||
Note Submitter: dave at davedelong dot com
----
A "cheap" way to sort a directory list is like so (outputs HTML, one indent is 3
non-breaking spaces):
<?php
function echo_Dir($dir, $level) {
//create an empty array to store the directories:
$dirs = array();
//if we were given a directory to list...
if (is_dir($dir)) {
//and if we can open it...
if ($handle = opendir($dir)) {
//change directory:
chdir($dir);
//iterate through the directory
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($file)) {
//only add legit directories to the array
array_push($dirs,$file);
}//end if
}//end if
}//end while
//sort the array
sort($dirs);
//NOW handle each directory via a foreach loop
foreach ($dirs as $i => $file) {
$to_echo = str_repeat("\t",$level+1) . str_repeat(" ",$level*3) .
$file . "<br>";
echo $to_echo;
echo_Dir($file,$level+1);
}//end foreach
//return to the parent directory
chdir("../");
}//end if
//close the handle
closedir($handle);
}//end if
}//end function
?>
For an example of what this outputs, check out http://www.davedelong.com/php/echodir.php