我正在解析來自網站的URL列表,並且想要構建嵌套數組的分層樹。遞歸構建可變深度的多維數組
我到目前爲止(哪些作品)如下。因爲我不知道關卡的深度會有多深,所以我會對深度進行一次簡單的檢查,然後執行一次基本檢測。
我該如何重寫它,以便適應任何數量的級別?
$tree = array();
$tree[$domain] = array(); // this is the domain root
foreach ($allMatches as $url) {
$foo = parse_url($url);
// trim "/" from beginning and end
$bar = trim($foo['path'],'/');
// for every "/", add a level
$parts = explode('/', $bar);
$parts = array_filter($parts, 'strlen');
// note: there is likely a bug in here.
// If I process page-1/page-1-1 before page-1,
// then the leaf or branch containing page-1-1 will be deleted
if (count($parts) == 1){
$tree[$domain][$parts[0]] = array();
}
if (count($parts) == 2){
$tree[$domain][$parts[0]][$parts[1]] = array();
}
if (count($parts) == 3){
$tree[$domain][$parts[0]][$parts[1]][$parts[2]] = array();
}
if (count($parts) == 4){
$tree[$domain][$parts[0]][$parts[1]][$parts[2]][$parts[3]] = array();
}
};
這些是輸入網址:
domain.com/page-1
domain.com/page-1/page-1-1
domain.com/page-1/page-1-1/page-1-1-1
domain.com/page-1/page-1-2
domain.com/page-1/page-1-1/page-1-2-1
domain.com/page-2
domain.com/page-2/page-2-1
注:我不一定需要有domain.com/page-2
在列表中,以產生domain.com/page-2/page-2-1
葉這是希望的產生結構:
Array
(
[domain.com] => Array
(
[page-1] => Array
(
[page-1-1] => Array
(
[page-1-1-1] => Array
(
)
)
[page-1-2] => Array
(
[page-1-2-1] => Array
(
)
)
)
[page-2] => Array
(
[page-2-1] => Array
(
)
)
)
)
你能提供一個輸入和期望輸出的例子嗎? – jake2389
如果你在列表中沒有'page-2',但是你有** page-2/page-2-1',你想創建父節點(即'page-2' ),還是你只想'page-1-2'作爲葉節點? – jake2389
我想在這種情況下創建父節點以及葉。 – limeygent