Код (PHP): <?php function scandirs($start) { $files = array(); $handle = opendir($start); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { if (is_dir($start.'/'.$file)) { $dir = scandirs($start.'/'.$file); $files[$file] = $dir; } else { array_push($files, $file); } } } closedir($handle); return $files; } ?>
PHP: <? $path = realpath('/etc'); $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); foreach($objects as $name => $object){ echo "$name\n"; } =)
не понял Код (Text): if( is_dir($outerDir."/".$d) ) $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d ); else $dir_array[ $d ] = $d;
[vs] прикалываешся чтоли? или я не догоняю? PHP: <? function ScanDirs($dir){ $res=array(); $fp=scandir($dir); if($fp[2]){ for($i=2,$c=count($fp);$i<$c;$i++){ if(is_dir($fd=$dir."/".$fp[$i])){ $res[$dir][$fd]=array_shift(ScanDirs($fd)); }else{ $res[$dir][]=$fp[$i]; } } } return $res; } ?>
Koc Я просто по заголовку посмотрел что про функцию scandir, комментарии не заметил. А моя функция самая быстрая =)
Mr.M.I.T. Всякие должны быть решения и алгоритмы в этом разделе. Я в свое время долго втыкал, как же директорию просканировать.
Недавно нужна была такая функция. В результате получилось тоже самое. Но предварительно я посмотрел как подобное реализовано в CMS Joomla, так вот там работа с папками и файлами осуществляется через FTP и при невозможности прибегают уже к функциям файловой системы. Интересно почему!? может так быстрее!?
N!k0 Не стоит брать примеры с опенсорсных продуктов. Большинство того, что я видел, просто хлам, работающий на соплях.
Kreker а откуда стоит брать примеры? имхо, процентное соотношение хлама в мире опенсорс и в мире клоузсорс одинаково.
достаточно лишь посмотреть на исходники DLE или Slaed Но порой использовать опенсорсные куски кода не стоит из-за лицензии на них
Сканирование с заданой глубиной Код (PHP): <?php function scandirs($start, $deep = false) { static $current_level = 0; $files = array(); $handle = opendir($start); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { if (is_dir($start.'/'.$file)) { if ($current_level === $deep) { continue; } $current_level++; $dir = scandirs($start.'/'.$file, $deep); $files[$file] = $dir; } else { array_push($files, $file); } } } closedir($handle); $current_level--; return $files; }
Попробовал написать что-то своё. Получил следующее: PHP: <?php function my_scandir( $dir, $deep = 0, $with_links = true) { // Current level static $level = 0; rtrim( $dir, '/'); // Delte slash in the end, if exists // Result array $result = array(); // If directory, cycling if( is_dir( $dir)) { $level++; // increasing deep level $result[] = $dir; // adding the directory to the results $dir .= '/'; if( is_readable( $dir)) // if we can read directy, { $files = scandir( $dir); // getting all files if( $deep == 0 || $level <= $deep) // deep restriction { foreach( $files as $file) { // adding to the result, if $with_links is true if( $file == '.' || $file == '..') { if( $with_links) $result[] = $dir .$file; continue; } // scanning, if it's directory *RECURSION* if( is_dir( $dir .$file)) $result = array_merge( $result, my_scandir( $dir .$file , $deep, $with_links)); // adding to the results if it's file else $result[] = $dir .$file; } } } } // If file, adding to the result array elseif( is_file( $dir)) $result[] = $dir; $level--; return $result; } ?>