2014-12-07 21 views
0

Using this way, DirectoryIterator週期
完成後,你會得到一個文件名列表,以後你就可以按字母順序排序,
這樣就可以處理從該列表中的文件名的每個文件 - 按字母順序排列。 ..現在PHP:如何使用DirectoryIterator處理文件_alphabetically_

,萬一,DirectoryIterator週期完成後,
你需要一個陣列(按文件名的字母順序排序),包含不僅是文件名
也是所有其他文件屬性小號,如:

  • 權限
  • 所有者
  • 創建時間
  • 大小
  • 等...

這裏的問題是,你不能DirectoryIterator週期的排序以前完成,
你將無法從您的列表訪問除文件名以外的任何後...

回答

0

DirectoryIterator對象提供一種訪問許多文件屬性的簡單方法。

$dir = new DirectoryIterator($path); 
foreach ($dir as $fileInfo) { 
    if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) { 
     /* You can access the file information inside this cycle */ 
     $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4); 
     echo $fileInfo->getFilename() . " " . $octal_perms . "\n"; 
    } 
} 

如果我們需要的的fileInfo對象DirectoryIterator週期完成後,
我們將不得不克隆(複製)所有這些DirectoryIterator對象到一個新的數組,
然後按字母順序排序這個數組通過DirectoryIterator對象的文件名屬性。

function cmp($a, $b) 
{ 
    return strcmp($a->getFilename(), $b->getFilename()); 
} 

$dir = new DirectoryIterator($path); 
foreach ($dir as $fileInfo) { 
    if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) { 
     /* we need to clone a fileInfo object into array, not just assign it */ 
     $allFilesInfo[] = clone $fileInfo; 
    } 
} 

/* Alphabetically sorting the array with DirectoryIterator objects, by filename */ 
usort($allFilesInfo, 'cmp'); 

foreach ($allFilesInfo as $fileInfo) { 
    /* Everything is alphabetical here ;) */ 
    $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4); 
    echo $fileInfo->getFilename() . " " . $octal_perms . "\n"; 
} 

^^在這最後一個週期,你可以用你的文件的工作按字母順序排列,
同時能夠訪問所有的屬性:)

注:在崩潰的情況下,由於「打開文件太多」錯誤導致,
增加操作系統中每個進程打開文件描述符的最大限制。
相關配置文件取決於您的操作系統,通常它們存儲在/ etc中

+0

「太多打開的文件」不應該被忽略。如果您遇到此類錯誤,您正在設法釋放/關閉資源。在不瞭解這種錯誤的原因的情況下,不應該簡單地提高極限。 – 2015-10-26 15:52:44