首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列出最后一级的文件夹和子文件夹php

列出最后一级的文件夹和子文件夹php
EN

Stack Overflow用户
提问于 2019-08-23 06:28:04
回答 1查看 42关注 0票数 1

我需要监视目录中是否有空文件夹,以便为用户生成警报。

由于infra的原因,我想在php中执行的这个脚本将每天运行一次。

我找到了几个例子,但没有一个能帮助我列出最后一层的空文件夹。

示例:

代码语言:javascript
复制
Root / Folder1 / year / month / file.pdf
Root / Pasta2 / year / month

在文件夹2中,我知道它是空的,我需要得到所有这些箱子。

我试过了

代码语言:javascript
复制
$di = new RecursiveDirectoryIterator('../Vistorias/');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}

结果:

代码语言:javascript
复制
../Vistorias/. - 256 bytes 
../Vistorias/.. - 416 bytes 
../Vistorias/.DS_Store - 14340 bytes 
../Vistorias/Pasta-3/. - 64 bytes 
../Vistorias/Pasta-3/.. - 256 bytes 
../Vistorias/Paste-2/. - 64 bytes 
../Vistorias/Paste-2/.. - 256 bytes 
../Vistorias/Pasta-1/. - 160 bytes 
../Vistorias/Pasta-1/.. - 256 bytes 
../Vistorias/Pasta-1/.DS_Store - 6148 bytes 
../Vistorias/Pasta-1/Sub-pasta-1-a/. - 96 bytes 
../Vistorias/Pasta-1/Sub-pasta-1-a/.. - 160 bytes 
../Vistorias/Pasta-1/Sub-pasta-1-a/export.pdf - 3959 bytes 
../Vistorias/Pasta-1/vazia/. - 64 bytes 
../Vistorias/Pasta-1/vazia/.. - 160 bytes 

我希望得到这样的回报:

代码语言:javascript
复制
../Vistorias/Pasta-3/. - 64 bytes 
../Vistorias/Paste-2/.. - 256 bytes 
../Vistorias/Pasta-1/Sub-pasta-1-a/export.pdf - 3959 bytes 
../Vistorias/Pasta-1/vazia/. - 64 bytes 
../Vistorias/teste/. - 96 bytes 
../Vistorias/teste/trigo.png - 1727287 bytes 

所以我知道下面的文件夹是空的:

代码语言:javascript
复制
../Vistorias/Pasta-3/. - 64 bytes 
../Vistorias/Paste-2/.. - 256 bytes 

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-23 15:19:07

这样如何-从文件名中提取路径,使用该路径作为数组的键,并汇总您遇到的目录条目的数量。对于空目录,由于条目...,该计数将为2。因此,任何其他具有不同计数的对象都可以使用array_filter从最终数组中删除。

代码语言:javascript
复制
$di = new RecursiveDirectoryIterator('../Vistorias/');
$folders = [];
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    $path = pathinfo($filename, PATHINFO_DIRNAME);
    // entry for path either already exists, then add one - or initialize with 1
    $folders[$path] = isset($folders[$path]) ? $folders[$path] + 1 : 1;
}
// filter all entries with a count != 2, and apply array_keys
// to get the folder names, which are currently the keys, to become the values
// again in the final result
$folders = array_keys(array_filter($folders, function($count) { return $count == 2; }));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57617731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档