-1

In my server I have folders and sub-directory

I want to call a flatten methode to a directory to move every files at the same level and remove all empty folders

Here is what i've done so far:

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;
    }

This code dont show any error on run, but the resukt is not as expected.

For exemple if I have /folder1/folder2/file I want to have /folder2/file as a result but here the folders still like they where ...

0x1gene
  • 3,349
  • 4
  • 29
  • 48

1 Answers1

0

I finally make my code works, I post it here in case it help someone

I simplified it to make it more efficient. By the way this function is part of a filemanager classe I made, so I use function of my own class, but you can simply replace $this->move($file, $destination); by 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);
               }
          }
     }
0x1gene
  • 3,349
  • 4
  • 29
  • 48