在php中使用opendir()按字母顺序排序和显示目录列表 [英] Sort and display directory list alphabetically using opendir() in php
问题描述
php noob here - 我已经拼凑了这个脚本来显示来自 opendir 文件夹中的图像列表,但我无法弄清楚如何(或在哪里)按字母顺序对数组进行排序
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!
推荐答案
您需要先将文件读入数组,然后才能对它们进行排序.这个怎么样?
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>
";
}
?>
这与您要问的内容无关,但是您可以使用 pathinfo() 函数也是如此.那时您将不需要硬编码的扩展数组,您可以删除任何扩展.
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.
这篇关于在php中使用opendir()按字母顺序排序和显示目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!