2017-02-04 5 views
1

私はウェブサイトから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を持っている必要はありません。構造:

+0

入力と出力の例を挙げることができますか? – jake2389

+0

リストに 'page-2'がなくても、' ** page-2/page-2-1'を持っていれば、親ノードを作成しますか( 'page-2') )、または 'page-1-2'だけをリーフノードとして使いたいですか? – jake2389

+0

この場合、親ノードとリーフを作成したいと思います。 – limeygent

答えて

1

これを行うには、再帰的あなたが参照として配列を渡すならば、関数は機能します。

$result = array(); 

function build_array(&$arr, $parts, $i = 0){ 
    if($i == sizeof($parts)) 
     return; 
    if(!isset($arr[$parts[$i]])) 
     $arr[$parts[$i]] = array(); 
    build_array($arr[$parts[$i]], $parts, $i+1); 
} 

# Call it like so: 
build_array($result, $parts); 

あなたが持っているURLごとにこの関数を呼び出してください。

ヒント:使用array_reduce

注:ユーザー入力を伴うWebコンテキストでこれを実行している場合は、深刻な制限が追加されます。

+0

優れています。 1小さな変更: $結果[$ドメイン] =配列(); ' そしてそれは魅力のように動作します。 – limeygent

関連する問題