如何使用php按字母顺序对文件夹目录进行排序 请帮助我解决这个问题,这不是[重复]帖子谢谢。
此代码如下所示(按时间排序)
- 狗
- 猫
- 橙
- 苹果
- 娃娃
- 鱼
- 飞机
- 香蕉
- 象
我想要这样
美国广播公司
- 飞机
- 苹果
- 苹果
- 香蕉
- 猫
DEF
- 狗
- 娃娃
- 象
- 鱼
PHP代码
<?php
function folderlist(){
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
sort($folders);
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
echo '<div class="menu">
<h3 class="headerbar"><a href="' .$path .'index2.php?folder=' .$name . '" class="style1"><span class="headertit">' .$name . '</span></a></div>';
}
?>
将
你对sort
的调用替换为如下内容:
usort($folders, function ($a, $b) {
return strnatcmp($a['name'], $b['name']);
});
此外,您可能希望通过使用目录迭代器或 scandir 来降低代码复杂性
你应该尝试使用 scandir()。 默认情况下,scandir() 将按字母顺序对文件进行排序:
$dir = './';
$files1 = scandir($dir);
print_r($files1);
http://php.net/manual/en/function.scandir.php