简体   繁体   English

如何一起计算几个文件夹中的所有文件

[英]how to count all files in a couple of folders together

In a directory called articles i have some .txt files in it and some subdirectories, which represent a year (like 2020 , 2019 , 2018 and so on...)在一个名为articles的目录中,我有一些.txt文件和一些子目录,它们代表一年(如202020192018等等......)

The structure looks like this:结构如下所示:

articles
   |-> 2020
        |-> 1.txt
            2.txt
            3.txt
   |-> 2019
        |-> 1.txt
            2.txt
            3.txt
   |-> 2018
        |-> 1.txt
            2.txt
            3.txt
   |-> main1.txt
       main2.txt
       main3.txt

How can i get the number of all txt files which are in the subdirectories (2020, 2019, 2018...)如何获取子目录中所有 txt 文件的数量(2020、2019、2018 ......)

I already have this:我已经有了这个:

$archive_years = array_filter(glob('articles/*'), 'is_dir'); // read dir only
foreach($archive_years as $archive_year) {
    echo count(glob($archive_year.'/*.txt')); // number of txt files form each year
   // how count number of txt files from all years together??
}

How about this?这个怎么样?

<?php
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/your/dir'));
$files = array();

foreach ($rii as $file) {
    if ($file->isDir() || pathinfo($file, PATHINFO_EXTENSION) != "txt") {
        continue;
    }
    
    if (!isset($files[$file->getPath()])) {
        $files[$file->getPath()] = 0;
    }
    
    $files[$file->getPath()]++;
    
}

var_dump($files);

For example, the following output is all the .cpp files in my project directory:比如下面的output就是我项目目录下的所有.cpp文件:

array(10) {
  ["mypath/src/networking"]=>
  int(2)
  ["mypath/src/thirdpart/rncryptor"]=>
  int(3)
  ["mypath/src/thirdpart/QProgressIndicator"]=>
  int(1)
  ["mypath/src/model"]=>
  int(4)
  ["mypath/src/views"]=>
  int(8)
  ["mypath/src/helper"]=>
  int(5)
  ["mypath/src/helper/deviceclient"]=>
  int(3)
  ["mypath/src/helper/deviceclient/qwe"]=>
  int(6)
  ["mypath/src/helper/view"]=>
  int(1)
  ["mypath/src"]=>
  int(1)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM