Confused about php recursion?
黄舟
黄舟 2017-06-30 09:56:06
0
2
851
function mkDirs1($path){
    if(is_dir($path)){//已经是目录了就不用创建
        return true;
    }
    if(is_dir(dirname($path))){//父目录已经存在,直接创建
        return mkdir($path);
    }
    mkDirs1(dirname($path));//从子目录往上创建
    return mkdir($path);//因为有父目录,所以可以创建路径
}
//mkDirs1('1/2/3/');

I searched this recursion on the Internet, and the more I read his comments, the more confused I became.
The following recursion has the same function as it


    $path = '11/22/33/44';
    // 归前的语句顺序执行,递归后的语句倒序执行
    function mkdirs($path)
    {
        if(is_dir($path)){
            return;
        }
        mkdirs( dirname($path) );
        return $path;
        // mkdir($path);
    }

    mkdirs($path);

Help analyze the difference between the following functions?
Is the first recursive comment correct?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
大家讲道理

The recursion in the example is correct. This can be replaced by a function: mkdir($sPath,0777,true); the third parameter is recursive creation

递归创建过程
//递归寻找文件夹存在的父级目录,假设存在的父级目录为11
//进行递归向上级寻找

11/22/33/44
11/22/33
11/22
11
11/22            //在最上级目录开始逐级创建子目录
11/22/33
11/22/33/44

这就是递归的执行过程
Ty80

The second one is wrong. You commented out mkdir. No matter how you recurse, you can’t create the directory, and the location of mkdir is wrong. It should be like this:

 function mkdirs($path)
    {
        if(is_dir($path)){
            return;
        }
        mkdirs( dirname($path) );
        mkdir($path);
        return $path;
    }

Regarding the explanation, you substitute the parameters and analyze step by step.
Try to analyze a few parameters and give it a try:
"./a"
"./a/b"
"./a/b/c"
"./a/b/c/d"
... ....

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template