-1

在我的服务器中,我有文件夹和子目录

我想将一个扁平化方法调用到一个目录以将每个文件移动到同一级别并删除所有空文件夹

这是我到目前为止所做的:

public function flattenDir($dir, $destination=null) {
        $files = $this->find($dir . '/*');
        foreach ($files as $file) {
            if(!$destination){
                $destination = $dir . '/' . basename($file);
            }
            if (!$this->isDirectory($file)) {
                $this->move($file, $destination);
            }else{
                $this->flattenDir($file, $destination);
            }
        }
        foreach ($files as $file) {
            $localdir = dirname($file);
            if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
                $this->remove($localdir);
            }
        }
    }


public function find($pattern, $flags = 0) {

        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
            $files = array_merge($files, $this->find($dir . '/' . basename($pattern), $flags));
        }

        return $files;
    }

此代码在运行时未显示任何错误,但结果与预期不符。

例如,如果我有/folder1/folder2/file我想要/folder2/file的结果,但这里的文件夹仍然像它们一样......

4

1 回答 1

0

我终于让我的代码工作了,我把它贴在这里以防它帮助别人

我简化了它以提高效率。顺便说一句,这个函数是我制作的文件管理器类的一部分,所以我使用我自己的类的函数,但你可以简单地替换$this->move($file, $destination);move($file, $destination);

public function flattenDir($dir, $destination = null) {
          $files = $this->find($dir . '/*');
          foreach ($files as $file) {
               $localdir = dirname($file);

               if (!$this->isDirectory($file)) {
                    $destination = $dir . '/' . basename($file);
                    $this->move($file, $destination);
               }
               if ($this->isDirectory($localdir) && $this->isEmptyDirectory($localdir) && ($localdir != $dir)) {
                    $this->remove($localdir);
               }
          }
     }
于 2013-06-13T12:37:44.740 回答