我有一個非常困難的時期搞清楚如何我可以遞歸遍歷數組,並創建一個數組的它的「路徑」遞歸通過數組進行迭代,並創建一個基於陣列的它的「路徑」
我有兩個陣列。一個是目錄樹的排列,看起來是這樣的:
$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',
];
我所做的嘗試都沒有真的讓我走得很遠。我試圖以遞歸方式遍歷數組時遇到卡住,但不知道下一步如何處理這個問題。
尾遞歸,傳遞一個變量,保留先前遍歷的元素的名稱,並在搜索時追加下一個元素。 –
當你的樹中不存在路徑時,你會做什麼?創建它還是不添加文件? (你也可能想要這樣做:https://3v4l.org/Ai9Uh) – Rizier123
應該總是有一條路徑。如果路徑不存在,我可能會想要拋出異常。請將您的解決方案作爲答案發布,以便在測試之後接受它 – Xecure