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

php noob здесь - я объединил этот script, чтобы отобразить список изображений из папки с 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);
}

?>

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

Ответы

Ответ 1

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

<?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(). Вам не понадобится жестко закодированный массив расширений, тогда вы можете удалить любое расширение.

Ответ 2

Использование 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\">";
}

Ответ 3

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

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";
}

Ответ 4

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

// strips files extensions      
$crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

$newstring = str_replace($crap, " ", $file );

Ответ 5

$directory = scandir('Images');