php案例:一个文件夹的彻底遍历

简介: php案例:一个文件夹的彻底遍历

前言

一、文件是什么?

存储数据的地方

二、使用步骤

1.引入库

代码如下(示例):

<?php
function countFilesInFolder($folderPath) {
    $fileCount = 0;
    $files = scandir($folderPath);
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        $filePath = $folderPath . '/' . $file;
        if (is_file($filePath)) {
            $fileCount++;
        } elseif (is_dir($filePath)) {
            $fileCount += countFilesInFolder($filePath);
        }
    }
    return $fileCount;
}
$folderPath = 'D:/666';  // 替换为实际的文件夹路径
$fileCount = countFilesInFolder($folderPath);
echo "文件夹中的文件数量:$fileCount";
/*核心思路在于:以0开始,如果是文件就累加1。如果是文件夹的话,就进入里面。把所有的文件连同之前的全部累加起来,*/

2.效果

总结

写完了,谢谢大家.


相关文章
|
3月前
|
网络协议 PHP