【发布时间】:2016-11-10 10:28:15
【问题描述】:
我很难弄清楚如何递归地遍历一个数组并创建一个它的“路径”数组
我有两个数组。一个是目录树的数组,看起来像这样:
$directoryTree = [
'accounting' => [
'documents' => [
],
'losses' => [
],
'profit' => [
]
],
'legal' => [
'documents' => [
]
]
];
另一个是指定文件应该驻留在哪个目录“路径”的文件列表:
$fileList = [
[
'name' => 'Overview.doc',
'dir_path' => []
],
[
'name' => 'Incorporation.doc',
'dir_path' => []
],
[
'name' => 'Profit And Loss.xls',
'dir_path' => ['accounting']
],
[
'name' => 'Profit 1.xls',
'dir_path' => ['accounting', 'profit']
],
[
'name' => 'Loss 1.xls',
'dir_path' => ['accounting', 'losses']
],
[
'name' => 'TOS Draft.doc',
'dir_path' => ['legal', 'documents']
]
[
'name' => 'Accounting Doc.pdf',
'dir_path' => ['accounting', 'documents']
],
];
基本上我要做的是遍历$directoryTree 并查看$fileList 中是否有任何元素具有迭代器所在的“路径”。如果有元素应该添加在那里。
最终的数组应该类似于this:
$finalOutput = [
'accounting' => [
'documents' => [
'Accounting Doc.pdf'
],
'losses' => [
'Loss 1.xls'
],
'profit' => [
'Profit 1.xls'
],
'Profit And Loss.xls'
],
'legal' => [
'documents' => [
'TOS Draft.Doc'
]
],
'Overview.doc',
'Incorporation.doc',
];
我所做的尝试并没有真正让我走得很远。我在尝试递归遍历数组时一直卡住,不知道接下来如何解决这个问题。
【问题讨论】:
-
尾递归,传递一个保留先前遍历的元素名称的变量,并在向下搜索时附加下一个。
-
当你的树中不存在路径时你会怎么做?创建还是不添加文件? (另外你可能想做这样的事情:3v4l.org/Ai9Uh)
-
应该总是有路径。如果路径不存在,我可能希望抛出异常。请将您的解决方案作为答案发布,以便我在测试后接受它
标签: php arrays recursion iterator