PHP实现递归目录的5种方法

2025-05-29 0 53

项目开发中免不了要在服务器上创建文件夹,比如上传图片时的目录,模板解析时的目录等。这不当前手下的项目就用到了这个,于是总结了几个循环创建目录的方法。

方法一:使用glob循环

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
<?php

//方法一:使用glob循环

function myscandir1($path, &$arr) {

foreach (glob($path) as $file) {

if (is_dir($file)) {

myscandir1($file . '/*', $arr);

} else {

$arr[] = realpath($file);

}

}

}

?>

方法二:使用dir && read循环

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
<?php

//方法二:使用dir && read循环

function myscandir2($path, &$arr) {

$dir_handle = dir($path);

while (($file = $dir_handle->read()) !== false) {

$p = realpath($path . '/' . $file);

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

$arr[] = $p;

}

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

myscandir2($p, $arr);

}

}

}

?>

方法三:使用opendir && readdir循环

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<?php

//方法三:使用opendir && readdir循环

function myscandir3($path, &$arr) {

$dir_handle = opendir($path);

while (($file = readdir($dir_handle)) !== false) {

$p = realpath($path . '/' . $file);

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

$arr[] = $p;

}

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

myscandir3($p, $arr);

}

}

}

?>

方法四:使用scandir循环

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<?php

//方法四:使用scandir循环

function myscandir4($path, &$arr) {

$dir_handle = scandir($path);

foreach ($dir_handle as $file) {

$p = realpath($path . '/' . $file);

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

$arr[] = $p;

}

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

myscandir4($p, $arr);

}

}

}

?>

方法五:使用SPL循环

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
<?php

//方法五:使用SPL循环

function myscandir5($path, &$arr) {

$iterator = new DirectoryIterator($path);

foreach ($iterator as $fileinfo) {

$file = $fileinfo->getFilename();

$p = realpath($path . '/' . $file);

if (!$fileinfo->isDot()) {

$arr[] = $p;

}

if ($fileinfo->isDir() && !$fileinfo->isDot()) {

myscandir5($p, $arr);

}

}

}

?>

可以用xdebug测试运行时间

?

1

2

3

4

5

6

7

8

9

10

11
<?php

myscandir1('./Code',$arr1);//0.164010047913

myscandir2('./Code',$arr2);//0.243014097214

myscandir3('./Code',$arr3);//0.233012914658

myscandir4('./Code',$arr4);//0.240014076233

myscandir5('./Code',$arr5);//0.329999923706

//需要安装xdebug

echo xdebug_time_index(), "\\n";

?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP实现递归目录的5种方法 https://www.kuaiidc.com/96016.html

相关文章

发表评论
暂无评论