我有这段代码:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'html')
{
$patterns = array();
$patterns[0] = '/_/';
$patterns[1] = '/.html/';
$patterns[2] = '/index/';
$replacements = array();
$replacements[2] = ' ';
$replacements[1] = '';
$replacements[0] = 'Strona główna';
$wynik = preg_replace($patterns, $replacements, $file);
$newVariable = str_replace("_", " ", $file);
$thelist .= '<li><a href="'.$file.'">'.ucfirst($wynik).'</a></li>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<P><?=$thelist?></p>
有没有办法按字母顺序显示文件列表?现在,该脚本在目录中列出了html文件。如何修改我可以手动设置目录的脚本?
//按字母顺序排列的代码:
<?php
if ($handle = opendir('.')) {
$files = glob("*");
foreach ($files as $file) // replace `while` with `foreach`
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'html')
{
$patterns = array();
$patterns[0] = '/_/';
$patterns[1] = '/.html/';
$patterns[2] = '/index/';
$replacements = array();
$replacements[2] = ' ';
$replacements[1] = '';
$replacements[0] = 'Strona główna';
$wynik = preg_replace($patterns, $replacements, $file);
$newVariable = str_replace("_", " ", $file);
$thelist .= '<li><a href="'.$file.'" target="_blank">'.ucfirst($wynik).'</a></li>';
}
}
closedir($handle);
}
?>
答案 0 :(得分:1)
尝试使用sort(...)
对数组进行排序。
答案 1 :(得分:1)
您可以使用glob()
代替opendir()
。除非被告知,否则Glob将对文件进行排序。
$files = glob("*");
foreach ($files as $file) // replace `while` with `foreach`
{
// the rest of your code
}
答案 2 :(得分:1)
我将文件信息添加到数组中,对数组进行排序,然后使用包含格式的循环回显信息。
答案 3 :(得分:0)
您可以使用SplHeap
foreach(new AlphabeticDir(__DIR__) as $file)
{
//Play Some Ball
echo $file->getPathName(),PHP_EOL;
}
班级
class AlphabeticDir extends SplHeap
{
public function __construct($path)
{
$files = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS);
foreach ($files as $file) {
$this->insert($file);
}
}
public function compare($b,$a)
{
return strcmp($a->getRealpath(), $b->getRealpath());
}
}