php递归和非递归,php 递归和非递归以及SPL遍历目录下的所有文件

//php 递归实现遍历 用dir 返回对象

function loop($dir){

$mydir =dir($dir);    //以对象的形式访问

while($file = $mydir ->read()){

//目录中有隐藏文件'.'和'..' 遍历的时候需要注意

if((is_dir("$dir/$file")) && ($file!=".") && ($file!="..")){

echo $file.'';

loop("$dir/$file"); //递归循环

}else{

if($file!=".." && $file!="."){

echo $file."";

}

}

}

}

loop(dirname(__FILE__));   //dirname 去掉文件名返回目录名

非递归处理遍历目录

思路: 首先创建一个数组,因为第一次传的是一个去掉文件名的目录名(如 c://wamp/www/php)

进行foreach 循环 所以第一次把C://wamp/www/php 下的全部文件都放入到了 数组中/只够进行 while大循环 每次输出数组的最后一个,当文件为目录的时候在此进行foreach循环

知道最后一个值时count($list)值为0 退出循环

function scanAll($dir)

{

$list = array();

$list[] = $dir;

while (count($list) > 0)

{

//  var_dump($list);

//弹出数组最后一个元素

$file = array_pop($list);

//处理当前文件

echo $file."";

//如果是目录

if (is_dir($file)){

$children = scandir($file);

var_dump($children);

foreach ($children as $child){

if ($child !== '.' && $child !== '..'){

$list[] = $file.'/'.$child;

}

}

}

}

}

scanAll(dirname(__FILE__));

PHP SPL 实现 遍历文件夹的文件

$path = dirname(__FILE__)."\\";  // 路径

echo $path."";

$directory = new RecursiveDirectoryIterator($path); //The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

$recursive = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::SELF_FIRST);

//各项都包含,例如递归文件夹就会连同子文件夹名称也作为其中项输出,顺序是先父后子

foreach($recursive as $file) {

echo str_repeat("\t", $recursive->getDepth()); // 获取当前的深度

if ($file->isDir()) {

echo DIRECTORY_SEPARATOR;

//DIRECTORY_SEPARATOR是php的内部常量,用于显示系统分隔符的命令,不需要任何定义与包含即可直接使用

}

echo $file->getBasename(); //Gets the base name of the file

if ($file->isFile()) {

echo "(" . $file->getSize() . "bytes)";

} else if ($file->isLink()) {  //判断是否是一个符号链接

echo "(symlink)";

}

echo "";

}

//echo $path;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值