Сортировка и отображение списка каталогов в алфавитном порядке с помощью 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);
}

?>

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

5 ответов


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

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

?>

Edit: это не связано с тем, что вы просите, но вы можете получить более общую обработку расширений файлов с помощью 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');