1

I've already asked about array creation with specific structure from directory structure (Create array from directory structure). Briefly. Now I have next directory structure:

  collection
      |
      |
      ---buildings
      |     |
      |     |
      |     |    
      |     ---2.php
      |     |
      |     ---4.php
      |
      |
      ---trees
          |
          |
          ---1.php
          |     
          ---2.php
          |
          ---3.php

I neet to iterate this directory structure and create next array:

array(
  0 => array('category' => 'trees',
         'file' => '3.jpg'
  ),
  1 => array('category' => 'trees', 
         'file' => '2.php'
  ),
  2 => array('category' => 'trees', 
         'file' => '1.jpg'
  ),
  3 => array('category' => 'buildings', 
         'file' => '2.jpg'
  ),
  4 => array('category' => 'buildings',
        'file' => '4.php'
  ))

So I've implemented it using RecursiveIterstorIterator and RecursiveDirectoryIterator. There is my code:

$path = __DIR__ . '/collection/';
$dir  = new RecursiveDirectoryIterator($path,     RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir,     RecursiveIteratorIterator::SELF_FIRST);
$index = 0;
$paths = [];

foreach ($files as $file) {

    $category = $paths[$index-1]['category'];

    if (strpos($file->getPathname(), $paths[$index-1]['category'])) {
        $paths[$index]['category'] = $paths[$index-1]['category'];
        $paths[$index]['file'] = $file->getFilename();
    }

    else {
        if ($paths[$index]['category']) {
            $paths[$index]['category'];
        } else {
            if ($file->isDir()) {
                $paths[$index]['category'] = $file->getFilename();
            }

            $files->next();

            $file = $files->current();

            if ($file->isFile()) {
                $paths[$index]['file'] = $file->getFilename();
            }
        }
    }

    $index++;
}

var_dump($paths);

But I think my code is 'dirty' and can use another functionality of RecursiveIteratorIterator and RecursiveDirectoryIterator avoid this awful if...else nesting. Also I think I didn't consider all usecases. So please could you please help me to refactor my code! Thanks!

1
  • If your code works and you'd like it to be reviewed, you can try Code Review. Commented May 23, 2023 at 12:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.