如何从平面数组创建多维树数组?

时间:2014-04-21 15:03:29

标签: php

'我有这个平面阵列:

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

我需要以下列格式:

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

我该怎么做?感谢。

2 个答案:

答案 0 :(得分:2)

递归是你的朋友: - )

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

继续向下钻取,直到找到文件名,然后将它们全部添加到一个数组中。

您需要为数组中的每个元素调用此函数,如下所示:

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

DEMO:https://eval.in/139240

答案 1 :(得分: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);