
PHP 函数中递归用于文件或目录遍历
递归是一种强大的编程技术,可以用于遍历文件或目录。在 PHP 中,我们可以使用 scandir() 函数来获取目录中的文件和子目录列表,然后使用递归函数来迭代遍历每个项目。
代码示例:
<?php
// 递归函数以遍历目录及其内容
function traverse($dir) {
// 打开目录句柄
if ($dh = opendir($dir)) {
// 读取目录中的每个文件或子目录
while (($file = readdir($dh)) !== false) {
// 跳过当前和上级目录
if ($file == '.' || $file == '..') {
continue;
}
// 如果是目录,则进行递归遍历
if (is_dir($file)) {
echo "$file is a directory:<br>";
traverse($file);
} else {
// 否则,只是输出文件名
echo "$file is a file:<br>";
}
}
// 关闭目录句柄
closedir($dh);
}
}
// 实战案例
$dir = 'path/to/directory';
traverse($dir);
?>输出:
立即学习“PHP免费学习笔记(深入)”;
directory1 is a directory: file1.txt is a file: file2.txt is a file: directory2 is a directory: file3.txt is a file: file4.txt is a file:
在这个示例中,traverse 函数从给定的目录开始,递归遍历其内容,并打印文件和子目录的名称。
以上就是PHP 函数中递归如何用于文件或目录的遍历?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号