使用php中的opendir()按字母顺序排列和显示目录列表 [英] Sort and display directory list alphabetically using opendir() in php
问题描述
php noob这里 - 我拼凑在一起这个脚本来显示一个包含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>\n";}
}
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>\n";
}
?>
编辑:这与您所要求的不相关,但您可以通过获取更一般的处理文件扩展名pathinfo()函数,你不需要硬编码的ext数组然后,您可以删除任何扩展名。
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屋!