2012-12-19 77 views
1

我有這樣的代碼:字母順序在循環

<?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文件。如何修改,我可以manualy設置目錄讀了劇本?

//代碼字母順序:

<?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); 
} 
?> 
+5

[你嘗試過什麼?](http://whathaveyoutried.com/) – DaveRandom

+0

我一直在尋找在谷歌,但我還沒有找到任何東西。 –

回答

1

你可以使用glob()代替opendir()。 Glob會對文件進行排序,除非被告知不要。

$files = glob("*"); 
foreach ($files as $file) // replace `while` with `foreach` 
{ 
    // the rest of your code 

} 
+0

@DanielKoczuła見我的編輯,你已經在陣列中的整個目錄,當你使用'水珠()',這樣你就不必使用'READDIR()'了。 – jeroen

+1

是的,現在它的工作; ) –

1

我想將文件信息添加到數組中,對數組進行排序,然後使用包含格式的循環回顯信息。

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()); 
    } 
}