PHP用迭代方法和递归方法创建级联目录(学习用,开发中应该写mkdir('./a/b/c/d/e',0777,true)
[php]
/*
用迭代的方法递归创建目录
其实在PHP5.0.0之后mkdir就已经能递归创建目录了。
这里主要是自己学习迭代,所以拿创建级联目录开刀了。
开发中应该写mkdir('./a/b/c/d/e',0777,true);
官方说明:
在 PHP 中可以调用递归函数。
但是要避免递归函数/方法调用超过 100-200 层,
因为可能会使堆栈崩溃从而使当前脚本终止。
*/
function it_mk_dir($path){
//定义一个数组,用来存放需要工作创建目录的任务
$arr = array();
//如果要创建的目录不存在,则表示有任务追加
while(!is_dir($path)){
array_unshift($arr,$path);
//将任务追加后取父目录
$path = dirname($path);
}
//如果没有任务(即:需要创建的目录已经存在)
if(empty($arr)){
return true;
}
//否则开始执行任务
foreach($arr as $k => $v){
//由上面的array_unshift压入方式,可直接这样调用
mkdir($v) ? print('创建'.$v.'目录成功!
'):print('创建失败->'.$v.'
');
}
return true;
}
[php]
/*
递归方法创建
*/
function mk_dir($path){
if(is_dir($path)){
return true;
}
//父目录存在或者是需要创建才能调用mkdir
return is_dir(dirname($path)) || mk_dir(dirname($path)) ? mkdir($path) : false;
}
it_mk_dir('./a/b/c/d/e/f/g');

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
