PHP中遍历目录的两种方法

  PHP中两种遍历某个目录下的子目录及文件的方法,遍历时主要是采用递归的算法,读某个目录下面的内容时,如果是目录,则递归遍历此目录,如果是文件,则将结果追加到数组中,同时数组用全局变量,定义在函数的外面,这样便于数组一直将结果递增起来

方法一

$dir = "e:/myphp/research/mailapi";
$dirs = array();

function scan_dir($dir) {
    global $dirs;
    if (!is_dir($dir)) return false;

    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file[0] == '.') continue;
            $fullpath = "$dir/$file";
            $dirs[] = $fullpath;
            if (is_dir($fullpath)) scan_dir($fullpath);           
        }
        closedir($dh);
    }

    return $dirs;
}
//scan_dir($dir);
//print_r($dirs);


方法二

function scan_dir2($dir) {
    global $dirs;
    if (!is_dir($dir)) return false;

    if ($dh = dir($dir)) {
        while (($file = $dh -> read()) !== false) {
            if ($file[0] == '.') continue;
            $fullpath = "$dir/$file";
            $dirs[] = $fullpath;
            if (is_dir($fullpath)) scan_dir2($fullpath);           
        }
        $dh->close();
    }

    return $dirs;
}
scan_dir2($dir);
print_r($dirs);


部分结果:
Array
(
    [0] => e:/myphp/research/mailapi/163
    [1] => e:/myphp/research/mailapi/163/163.php
    [2] => e:/myphp/research/mailapi/baseclass
    [3] => e:/myphp/research/mailapi/baseclass/baseclass.php
    [4] => e:/myphp/research/mailapi/gmail
    [5] => e:/myphp/research/mailapi/gmail/9063271b89460d5d4395cdfae8994089
    [6] => e:/myphp/research/mailapi/gmail/gmail-lite
    [7] => e:/myphp/research/mailapi/gmail/gmail-lite/chat.gif
    [8] => e:/myphp/research/mailapi/gmail/gmail-lite/clip.gif
    [9] => e:/myphp/research/mailapi/gmail/gmail-lite/compose.php
    [10] => e:/myphp/research/mailapi/gmail/gmail-lite/config.php
    [11] => e:/myphp/research/mailapi/gmail/gmail-lite/diagnose.php
    [12] => e:/myphp/research/mailapi/gmail/gmail-lite/dl.php
    [13] => e:/myphp/research/mailapi/gmail/gmail-lite/favicon.ico
    [14] => e:/myphp/research/mailapi/gmail/gmail-lite/glite.css
...
...
    [15] => e:/myphp/research/mailapi/gmail/gmail-lite/index.php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值