keonovic
keonovic

Reputation: 47

How do I create a multidimensional tree array from a flat array?

'I have this flat array:

$folders = [
  'test/something.txt',
  'test/hello.txt',
  'test/another-folder/myfile.txt',
  'test/another-folder/kamil.txt',
  'test/another-folder/john/hi.txt'
]

And I need it in the following format:

$folders = [
  'test' => [
     'something.txt',
     'hello.txt',
     'another-folder' => [
       'myfile.txt',
       'kamil.txt',
       'john' => [
         'hi.txt'
       ]
     ]
   ]
];

How do I do this? Thanks.

Upvotes: 2

Views: 88

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

<?php

$folders = [
    'test/something.txt',
    'test/hello.txt',
    'test/another-folder/myfile.txt',
    'test/another-folder/kamil.txt',
    'test/another-folder/john/hi.txt'
];

$new_folders = array();

foreach ($folders as $folder) {
    $reference =& $new_folders;
    $parts = explode('/', $folder);
    $file = array_pop($parts);

    foreach ($parts as $part) {
        if(!isset($reference[$part])) {
            $reference[$part] = [];
        }
        $reference =& $reference[$part];
    }
    $reference[] = $file;
}

var_dump($new_folders);

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

Recursion is your friend :-)

function createArray($folders, $output){
  if(count($folders) > 2){
    $key = array_shift($folders);
    $output[$key] = createArray(
      $folders, isset($output[$key]) ? $output[$key] : []
    );
  }
  else{
    if(!isset($output[$folders[0]])){
      $output[$folders[0]] = [];
    }
    $output[$folders[0]][] = $folders[1];
  }

  return $output;
}

Keep drilling down until you get to the file name, then add them all together in an array.

You need to call this function for each element in your array, like this:

$newFolders = [];
foreach($folders as $folder){
  $newFolders = createArray(explode('/', $folder), $newFolders);
}

DEMO: https://eval.in/139240

Upvotes: 2

Related Questions