2

'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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1
<?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);

1 Comment

I like the array_pop for the filename, going to merge my answer into yours since they're similar

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.