2019-03-26 20:02

# 如何在数组中创建层次结构？

I know I'm not describing well my question, but I want to create "nested array" as you can see:

folder/ -> folder/file.txt, folder/folder2/ -> folder/folder2/file.txt, folder/folder2/folder3/ -> etc

``````E:\wamp\www\index.php:31:
array (size=3)
'folder/' =>
array (size=1)
0 => string 'folder/file.txt' (length=15)
'folder/folder2/' =>
array (size=1)
0 => string 'folder/folder2/file.txt' (length=23)
'folder/folder2/folder3/' =>
array (size=1)
0 => string 'folder/folder2/folder3/file.txt' (length=31)
``````

My code is:

``````\$array = [
'folder/',
'folder/folder2/folder3/',
'folder/folder2/',
'folder/folder2/folder3/file.txt',
'folder/folder2/file.txt',
'folder/file.txt'
];
sort(\$array);
\$array = array_flip(\$array);
function recursive_dir_nested(\$a) {
foreach (\$a as \$k => \$v) {
if (preg_match("/\/\$/", \$k)) {
\$a[\$k] = [];
}

if (preg_match("/\/[^\/]+\$/", \$k)) {
\$nk = preg_replace("/\/[^\/]+\$/", "/", \$k);
if (array_key_exists(\$nk, \$a)) {
\$a[\$nk][] = \$k;
unset(\$a[\$k]);
} else {
recursive_dir_nested(\$a);
}
}
}

return \$a;
}
``````

I know I do something wrong, I'm not sure why... How can I solve this?

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 2条回答

• drcmg28484 2年前

Not sure if using regex's is the best way to go. This builds on another answer - PHP - Make multi-dimensional associative array from a delimited string, but adds in the idea of using an array of entries. The one thing to note is that when adding new entries, if the element isn't currently an array, it turns it into an array so it can contain multiple entries ( the `if ( !is_array(\$current) ) {` part).

It uses each string and builds the folder hierarchy from that, saving the last part as the file name to be added specifically to the folder element...

``````\$array = [
'folder/',
'folder/folder2/folder3/',
'folder/folder2/',
'folder/folder2/folder3/file.txt',
'folder/folder2/file.txt',
'folder/file.txt'
];
sort(\$array);

\$output = [];
foreach ( \$array as \$entry )   {
\$split = explode("/", \$entry);
\$current = &\$output;
\$file = array_pop(\$split);
foreach ( \$split as \$level )    {
if ( !isset(\$current[\$level]) ){
if ( !is_array(\$current) )  {
\$current = [ \$current ];
}
\$current[\$level] = [];
}
\$current = &\$current[\$level];
}
if ( !empty(\$file) )    {
\$current = \$file;
}
}

print_r(\$output);
``````

This gives you...

``````Array
(
[folder] => Array
(
[0] => file.txt
[folder2] => Array
(
[0] => file.txt
[folder3] => file.txt
)

)

)
``````
点赞 评论 复制链接分享
• dongshenjie3055 2年前

You can nest arrays in PHP. You might also want to use keys for the names of the directories:

``````\$array = [
'folder' => [
'folder2' => [
'folder3' => [
'file.txt'
],
'file.txt'
],
'file.txt'
]
];
``````

You could check each item with `is_array()` to see if it itself is array, then treat it as a string if it isn't.