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

标签 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'
       ]
     ]
   ]
];

我该怎么做?谢谢。

最佳答案

递归是你的 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;
}

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

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

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

演示:https://eval.in/139240

关于php - 如何从平面数组创建多维树数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199995/

相关文章:

javascript - ajax 完成后,加载 <script> 标签,但仅加载具有特定 id 的标签

php - 基本的 PHP SQL 查询不起作用

php - codeigniter 错误日志文件仅显示通知错误但错误消息未显示在屏幕上

php - 让 .get() 在 jquery 中工作

php - 在第 77 行 C : syntax error, php 中解析错误 :\wamp\www\Nu-Bio\view_topic. 意外 T_RETURN

php - 访问另一个 PHP 文件中的 POST 变量

php - 扩展 Doctrine2 形式 EntityType

php - preg_replace this : {{1}{2}{3}{. .}} -- 可能是一个简单的 PHP/preg_replace/RegEx 问题,但我真的很难过

php - codeigniter 是否在 http 请求之间共享 mysql session

php - 移动jquery onclick不播放音频文件?