私はウェブサイトからURLのリストを解析しており、ネストされた配列の階層ツリーを構築したいと考えています。可変深度の多次元配列を再帰的に構築する
私がこれまでに持っていることは、以下の通りです。私はレベルがどれだけ深いかわからないので、深さを簡単にチェックしてから、そのノードに基本的なプッシュを実行します。
これを書き換えてどのレベルのレベルに対応できますか?
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
注:
$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();
}
};
これらは入力URLです私は必ずしもこれが結果として求められるdomain.com/page-2/page-2-1
のための葉を生成するために、リストにdomain.com/page-2
を持っている必要はありません。構造:
入力と出力の例を挙げることができますか? – jake2389
リストに 'page-2'がなくても、' ** page-2/page-2-1'を持っていれば、親ノードを作成しますか( 'page-2') )、または 'page-1-2'だけをリーフノードとして使いたいですか? – jake2389
この場合、親ノードとリーフを作成したいと思います。 – limeygent