1

How do i convert multidimensional array to file path. I have this array :

$data = [
        "users" => [
                "joe" => [
                        "photos" => ["a.jpg","b.jpg"],
                        "files" => ["a.doc","b.doc"]
                ],
                "annie" => [
                    "photos" => ["a.jpg","b.jpg"],
                    "files" => ["a.doc","b.doc"]
                ],
        ]
];

that i must convert to path example :

"users/joe/photos/a.jpg";
"users/joe/photos/b.jpg";
"users/joe/files/a.doc";
"users/joe/files/b.doc";

"users/annie/photos/a.jpg";
"users/annie/photos/b.jpg";
"users/annie/files/a.doc";
"users/annie/files/b.doc";

But i can't have the best result with this functions :

$path = "";
function iterate($data, $path)
{
  echo "<br>";
    foreach ($data as $key => $item){
        if (is_array($item)){
            $path .= $key.DIRECTORY_SEPARATOR;
            iterate($item, $path);
        }else{
            echo $path.$item."<br>";
        }
    }
}

output :

users/joe/photos/a.jpg
users/joe/photos/b.jpg

users/joe/photos/files/a.doc
users/joe/photos/files/b.doc

users/joe/annie/photos/a.jpg
users/joe/annie/photos/b.jpg

users/joe/annie/photos/files/a.doc
users/joe/annie/photos/files/b.doc

Please help.

Thanks

kimpak
  • 15
  • 5

1 Answers1

0

You could make use of RecursiveIteratorIterator + RecursiveArrayIterator:

function computeFilePaths(array $fileTree): array
{
  $filePaths = [];

  $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fileTree));
  foreach ($iterator as $fileName) {
    for ($folders = [], $pos = 0, $depth = $iterator->getDepth(); $pos < $depth; $pos++) {
      $folders[] = $iterator->getSubIterator($pos)->key();
    }
    $filePaths[] = implode('/', $folders) . '/' . $fileName;
  }

  return $filePaths;
}

print_r(computeFilePaths($yourArrayGoesHere));

I highly suggest this question's selected answer to understand how these iterators work.

Jeto
  • 14,596
  • 2
  • 32
  • 46