递归复制合并文件夹内文件

php php 文件操作 1126      收藏
递归复制合并文件夹内文件

递归方法实现:

function mergeCopyDir1($source,$destination){
    if(is_dir($source) && is_dir($destination)){
        $sourceHandle = dir($source);
        while($s = $sourceHandle->read()){
            if(in_array($s, array('.','..'))){
                continue;
            }
            if(is_dir($source.'/'.$s)){
                if(!is_dir($destination.'/'.$s)){
                    mkdir($destination.'/'.$s);
                }
                $callee = __FUNCTION__;
                $callee($source.'/'.$s,$destination.'/'.$s);
            }else{
                if(@!copy($source.'/'.$s, $destination.'/'.$s)){
                    echo 'fail: '.$source.'/'.$s."\n";
                }
            }
        }
        return true;
    }else{
        return false;
    }
}



非递归方法实现:

function mergeCopyDir2($source,$destination){
    $queue = array();
    if(is_dir($source) && is_dir($destination)){
        array_push($queue, array($source,$destination));
    }else{
        return false;
    }
    while(!empty($queue)){
        $current = array_shift($queue);
        $source = $current[0];
        $destination = $current[1];
        $sourceHandle = dir($source);
        while($s = $sourceHandle->read()){
            if(in_array($s, array('.','..'))){
                continue;
            }
            if(is_dir($source.'/'.$s)){
                if(!is_dir($destination.'/'.$s)){
                    mkdir($destination.'/'.$s);
                }
                array_push($queue, array($source.'/'.$s,$destination.'/'.$s));
            }else{
                if(@!copy($source.'/'.$s, $destination.'/'.$s)){
                    echo 'fail: '.$source.'/'.$s."\n";
                }
            }
        }
    }
    return true;
}