簡體   English   中英

計算目錄中的文件,但排除子目錄

[英]Count files in directory, but exclude subdirectories

我發現了一個舊帖子,其中包含了我的問題幾乎完美的代碼:計算目錄中的(多個)文件。 它排除了。 en ..條目,但不是其他目錄。 我通過添加評論添加了一個問題,但沒有得到答復。 (太老的帖子,我想)( 計算目錄php中的文件數量

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

在php.net上搜索過,但很多這個主題都沒有記錄。 我確實找到了SKIP_DOTS事實,但沒有找到關於如何排除目錄的一封信。

現在我的代碼生成:有76849個文件,但這也包括子目錄。

如何更改此代碼,以便排除我的子目錄?

更新因為一些答案

/**
PHP version problem, need update first

$files = new FilesystemIterator('images');
$filter= new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
printf('There were %d Files', iterator_count($filter));
*/


$time0 = time();

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);

$fileCount = 0;
foreach ($fi as $f) {
    if ($f->isFile()) {
        $fileCount++;
    }
}
printf("xThere were %d Files", $fileCount);

$time1 = time();
echo'<br />tijd 1 = '.($time1 - $time0); // outcome 5

echo'<hr />'; 


$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);
printf("yThere were %d Files", iterator_count($fi));
$time2 = time();
echo'<br />tijd 2 = '.($time2 - $time1); // outcome: 0

我現在無法使用的第一個答案,因為我必須更新我的PHP版本。 在測量時間時,第二個答案需要更多的時間來處理。

我還注意到,由於第二個答案,我自己的代碼不計算子目錄中的文件,它只計算子目錄的數量,在我的情況下只是4.所以對於速度,我將使用我自己的代碼和它的4。 下周我嘗試更新我的php版本,並將再試一次。

謝謝大家的貢獻!

這很容易使用CallbackFilterIterators(自5.4起可用):

$files = new FilesystemIterator('images');
$filter= new CallbackFilterIterator($files, function($cur, $key, $iter) {
    return $cur->isFile();
});

printf('There were %d Files', iterator_count($filter));

更簡單,假設文件有擴展名,而目錄則沒有:

$count = count(glob('images/*.*'));

或者過濾掉目錄:

$count = count(array_diff(glob('images/*'), glob('images/*', GLOB_ONLYDIR)));

我會這樣做:

$fi = new FilesystemIterator(images, FilesystemIterator::SKIP_DOTS);

$fileCount = 0;
foreach ($fi as $f) {
    if ($f->isFile()) {
        $fileCount++;
    }
}
printf("There were %d Files", $fileCount);

當您閱讀它時,感覺就像自我記錄代碼。

Symfony的“ Finder ”組件非常靈活,它通過直觀的流暢界面查找文件和目錄(實際上它是許多SPL組件的包裝)。 大約30種方法可以配置結果。 例如:size,depth,exclude,ignoredotfiles,path,exclude,followLinks ........從文檔中獲取的示例:

use Symfony\Component\Finder\Finder ;
$finder = new Finder();
$iterator = $finder
  ->files()
  ->name('*.php')
  ->depth(0)
  ->size('>= 1K')
  ->in(__DIR__);

foreach ($iterator as $file) {
    print $file->getRealpath()."\n";
}

“文件”組件甚至可以用於遠程存儲的文件(如亞馬遜的S3)。 將“symfony / finder”:“2.3.*@dev”編寫到composer.json文件並運行“composer update”CLI命令時,安裝非常簡單。 到目前為止,該組件的安裝量已達到140萬次,是其質量的最佳證據。 許多框架/項目在幕后使用此組件。

$ fi = new FilesystemIterator( DIR 。'/ images',FilesystemIterator :: SKIP_DOTS); printf(“有%d文件”,iterator_count($ fi));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM