Сортировка и отображение списка каталогов по алфавиту с помощью opendir () в php

php noob здесь – я объединил этот скрипт, чтобы отобразить список изображений из папки с opendir, но я не могу понять, как (или где) сортировать массив по алфавиту

<?php // opens images folder if ($handle = opendir('Images')) { while (false !== ($file = readdir($handle))) { // strips files extensions $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file ); //asort($file, SORT_NUMERIC); - doesnt work :( // hides folders, writes out ul of images and thumbnails from two folders if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </a></li>\n";} } closedir($handle); } ?> 

Любые советы или указатели были бы высоко оценены!

Прежде чем вы сможете сортировать их, вам необходимо прочитать свои файлы в массиве. Как насчет этого?

 <?php $dirFiles = array(); // opens images folder if ($handle = opendir('Images')) { while (false !== ($file = readdir($handle))) { // strips files extensions $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file ); //asort($file, SORT_NUMERIC); - doesnt work :( // hides folders, writes out ul of images and thumbnails from two folders if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { $dirFiles[] = $file; } } closedir($handle); } sort($dirFiles); foreach($dirFiles as $file) { echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </a></li>\n"; } ?> 

Изменить: это не связано с тем, что вы просите, но вы можете получить более общую обработку расширений файлов с помощью функции pathinfo () . Вам не понадобится жестко закодированный массив расширений, тогда вы можете удалить любое расширение.

Использование opendir()

opendir() не позволяет сортировать список. Вам придется выполнять сортировку вручную. Для этого сначала добавьте все имена файлов в массив и отсортируйте их с помощью sort() :

 $path = "/path/to/file"; if ($handle = opendir($path)) { $files = array(); while ($files[] = readdir($dir)); sort($files); closedir($handle); } 

И затем перечислите их, используя foreach :

 $blacklist = array('.','..','somedir','somefile.php'); foreach ($files as $file) { if (!in_array($file, $blacklist)) { echo "<li>$file</a>\n <ul class=\"sub\">"; } } 

Использование scandir()

С scandir() это намного проще. Он выполняет сортировку по умолчанию. Та же функциональность может быть достигнута с помощью следующего кода:

 $path = "/path/to/file"; $blacklist = array('somedir','somefile.php'); // get everything except hidden files $files = preg_grep('/^([^.])/', scandir($path)); foreach ($files as $file) { if (!in_array($file, $blacklist)) { echo "<li>$file</a>\n <ul class=\"sub\">"; } } 

Использование DirectoryIterator (предпочтительно)

 $path = "/path/to/file"; $blacklist = array('somedir','somefile.php'); foreach (new DirectoryIterator($path) as $fileInfo) { if($fileInfo->isDot()) continue; $file = $path.$fileInfo->getFilename(); echo "<li>$file</a>\n <ul class=\"sub\">"; } 

Так я бы это сделал

 if(!($dp = opendir($def_dir))) die ("Cannot open Directory."); while($file = readdir($dp)) { if($file != '.') { $uts=filemtime($file).md5($file); $fole_array[$uts] .= $file; } } closedir($dp); krsort($fole_array); foreach ($fole_array as $key => $dir_name) { #echo "Key: $key; Value: $dir_name<br />\n"; } 

Примечание. Переместите это в цикл foreach, чтобы переменная newstring была переименована правильно.

 // strips files extensions $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file ); 
 $directory = scandir('Images');