PHP 遍历文件夹下的文件以及子文件夹

本文介绍了使用PHP实现目录遍历的两种方法:一种是通过递归函数实现;另一种则是利用队列的方式完成。递归方法中,对于每个子目录都进行递归调用,收集所有文件名。而在队列方式中,则将所有待处理的目录路径加入队列,并逐步处理,直至队列为空。这两种方法各有优劣,可根据具体需求选择。

// 递归的方式实现
function my_dir( $dir )
{
  if ( !is_dir($dir) )
  {
    return 'not dir';die();
  }
  $files = array();
  $dir_list = scandir($dir);
  foreach( $dir_list as $file )
  {
    if( $file!='.' && $file!='..' )
    {
      if( is_dir( $dir.'/'.$file ))
      {
        $files[$file] = my_dir( $dir.'/'.$file );
      }
      else
      {
        $files[] = $file;
      }
    }
  }
  return $files;
};

 

// 队列方式实现

function my_dir_list( $dir )
{
  if( !is_dir( $dir) )
  {
    return 'not dir';die();
  }
  $files = array();
  $queue = array( $dir );
  // $data = each( $queue );
  while( $data = each( $queue) )
  {
    $path = $data['value'];
    $handle = opendir( $path );
    if( is_dir($path) && $handle )
    {
      // $file = readdir( $handle );
      while( $file = readdir( $handle) )
      {
        if ( $file == '.' || $file == '..' )
        {
          continue;
        }
        else
        {
          $real_path = $path.'/'.$file;
          $files[] = $real_path;
          if( is_dir($real_path) )
          {
            $queue[] = $real_path;
          }
        }
      }
    }
    closedir($handle);
  }
  return $files;
}

 

转载于:https://www.cnblogs.com/laowenBlog/p/6531487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值