Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

sorting - Sort and display directory list alphabetically using opendir() in php

php noob here - I've cobbled together this script to display a list of images from a folder with opendir, but I can't work out how (or where) to sort the array alphabetically

<?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>
";}
}
closedir($handle);
}

?>

Any advice or pointers would be much appreciated!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to read your files into an array first before you can sort them. How about this?

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

?>

Edit: This isn't related to what you're asking, but you could get a more generic handling of file extensions with the pathinfo() function too. You wouldn't need a hard-coded array of extensions then, you could remove any extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...