【发布时间】:2015-08-24 13:00:16
【问题描述】:
我有一个这样的数组:
$arr = array(
'home.js' => new File(),
'view/index.html' => new File(),
'src/index.js' => new File(),
'src/libs/jquery.js' => new File()
);
现在我想转换成这样的结构:
Array
(
[0] => Array
(
[text] => home.js
)
[1] => Array
(
[text] => view
[children] => Array
(
[0] => Array
(
[text] => index.html
)
)
)
[2] => Array
(
[text] => src
[children] => Array
(
[0] => Array
(
[text] => index.js
)
[1] => Array
(
[text] => libs
[children] => Array
(
[0] => Array
(
[text] => jquery.js
)
)
)
)
)
)
在 StackOverfow 答案的帮助下,我尝试了几个小时,但我无法找到解决方案,因为所有其他问题都有不同的设置。
编辑:
到目前为止,在 SO 的帮助下我得到的是(虽然不记得确切的答案):
$out = array();
foreach($arr as $path => $file) {
$parts = explode('/', trim($path, '/'));
applyChain($out, $parts, $file);
}
function applyChain(&$arr, $parts, $value)
{
if (!is_array($parts)) {
return;
}
if (count($parts) == 0) {
$arr = $value;
} else {
array_shift($parts);
applyChain($arr[], $parts, $value);
}
}
print_r($out);
我不知道它是如何工作的,尤其是applyChain($arr[] ... 部分)。它有点适用于深度,但不适用于文件名。我得到以下输出:
Array
(
[0] => File Object
(
)
[1] => Array
(
[0] => File Object
(
)
)
[2] => Array
(
[0] => File Object
(
)
)
[3] => Array
(
[0] => Array
(
[0] => File Object
(
)
)
)
)
【问题讨论】:
-
递归函数和爆炸可能会有所帮助。顺便说一句,到目前为止你尝试过什么?
-
我用迄今为止的尝试编辑了我的问题。
标签: php multidimensional-array structure flat