为PHP遍历目录和文件列表编写一个简单的类,并使用一个示例,并使用它作为参考。

复制代码代码如下所示:
< PHP
定义('ds ',directory_separator);

类getdirfile {

返回
私人dirarray美元=阵();
私人filearray美元=阵();
私人dirfilearray美元=阵();

私有$句柄,$目录,$文件;

获取目录列表
公共功能getdir($dir){
如果(is_dir($dir)){
如果(假)!=($处理= opendir($dir))){
(假)!=($文件= readdir($处理))){
如果(文件$ ==!!!strpos(文件的)){
dirarray美元{ } =文件;
}
}
closedir($处理);
}
其他{ }
$DirArray{} ='{Path}: ''.$Dir.''is not a dir or not found!
}
返回的dirarray;
}

获取文件列表
Public function getFile ($Dir) {
如果(is_dir($dir)){
如果(假)!=($处理= opendir($dir))){
(假)!=($文件= readdir($处理))){
如果美元($文件文件strpos = '。!=…($文件)
filearray美元{ } =文件;
}
}
closedir($处理);
}
其他{ }
filearray美元{ } ={路}:。$dir。不是一个目录或未找到!
}
返回的filearray;
}

获取目录/文件列表
公共功能getdirfile($dir){
如果(is_dir($dir)){
dirfilearray美元{ 'dirlist} =美元-> getdir($dir);
如果($ dirfilearray){
foreach($ dirfilearray { 'dirlist}达处理){
一个文件;
dirfilearray { } { 'filelist美元的美元处理} =美元-> GetFile(文件);
}
}
其他{ }
dirfilearray美元{ } ={路}:。$dir。不是一个目录或未找到!
}
返回的dirfilearray;
}

}
>


示例:(相对路径或绝对路径)

1。获取目录列表
复制代码代码如下所示:
< PHP
dir_dir美元= ',说';
getdirfile美元=新getdirfile();
getdir美元=美元getdirfile -> getdir($ dir_dir);
print_r($ getdir);
>


显示
复制代码代码如下所示:
< PHP
file_one_dir美元= '。 / / example_one的例子;
file_two_dir美元= E: / / /工作区mycode getdirfile / / example_two的例子;

getdirfile美元=新getdirfile();
getfile_one美元=美元getdirfile -> GetFile($ file_one_dir);
getfile_two美元=美元getdirfile -> GetFile($ file_two_dir);

print_r($ getfile_one);
print_r($ getfile_two);
>


2。获取文件列表
复制代码代码如下所示:
< PHP
file_one_dir美元= '。 / / example_one的例子;
file_two_dir美元= E: / / /工作区mycode getdirfile / / example_two的例子;

getdirfile美元=新getdirfile();
getfile_one美元=美元getdirfile -> GetFile($ file_one_dir);
getfile_two美元=美元getdirfile -> GetFile($ file_two_dir);

print_r($ getfile_one);
print_r($ getfile_two);
>


显示
复制代码代码如下所示:
阵列
(
{ 0 } = > example.sql
{ 1 } = > example.txt
)

阵列
(
{ 0 } = > example.php
)


三.获取目录/文件的列表
复制代码代码如下所示:
< PHP
dir_dir美元= ',说';

getdirfile美元=新getdirfile();
getdirfile美元=美元getdirfile -> getdirfile($ dir_dir);

print_r($ getdirfile);
>


显示
复制代码代码如下所示:
阵列
(
{取} = >阵列
(
{ 0 } = > example_one
{ 1 } = > example_two
)

{ } = >数组文件列表
(
{ example_one } = >阵列
(
{ 0 } = > example.sql
{ 1 } = > example.txt
)

{ example_two } = >阵列
(
{ 0 } = > example.php
)
)
)