3 回答
![?](http://img1.sycdn.imooc.com/545865da00012e6402200220-100-100.jpg)
TA贡献1843条经验 获得超7个赞
您需要先将文件读入数组,然后才能对它们进行排序。这个怎么样?
<?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()函数对文件扩展名进行更通用的处理。然后,您不需要扩展的硬编码数组,就可以删除任何扩展。
![?](http://img1.sycdn.imooc.com/545863c10001865402200220-100-100.jpg)
TA贡献1790条经验 获得超9个赞
使用 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\">";
}
![?](http://img1.sycdn.imooc.com/533e4c1500010baf02200220-100-100.jpg)
TA贡献2065条经验 获得超14个赞
这就是我会做的方式
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";
}
- 3 回答
- 0 关注
- 787 浏览
添加回答
举报