'我有这个平面数组:
$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);
}
关于php - 如何从平面数组创建多维树数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23199995/