簡體   English   中英

如何從平面數組創建多維樹數組?

[英]How do I create a multidimensional tree array from a 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'
]

我需要以下格式:

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

我該怎么做呢? 謝謝。

遞歸是你的朋友:-)

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

$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM