从URL构建阵列树

时间:2010-06-22 14:48:40

标签: php tree

我需要从给定的URL构建一个树(带有数组)。

我有以下网址列表:

http://domain.com/a/a.jsp
http://domain.com/a/b/a.jsp
http://domain.com/a/b/b.jsp
http://domain.com/a/b/c.jsp
http://domain.com/a/c/1.jsp
http://domain.com/a/d/2.jsp
http://domain.com/a/d/a/2.jsp

现在我需要一个这样的数组:

domain.com
  a
    a.jsp
    b
      a.jsp
      b.jsp
      c.jsp
    c
      1.jsp
    d
      2.jsp
      a
        2.jsp

我怎么能用PHP做到这一点?

2 个答案:

答案 0 :(得分:2)

我认为马克的解决方案有点复杂,所以这是我的看法:

注意:当你到达URI的文件名部分时,我将其设置为键和值,不确定那里有什么,嵌套样本没有给予很多见解。)

<?php

$urls = array(
    'http://domain.com/a/a.jsp',
    'http://domain.com/a/b/a.jsp',
    'http://domain.com/a/b/b.jsp',
    'http://domain.com/a/b/c.jsp',
    'http://domain.com/a/c/1.jsp',
    'http://domain.com/a/d/2.jsp',
    'http://domain.com/a/d/a/2.jsp'
);

$array = array();

foreach ($urls as $url)
{
    $url = str_replace('http://', '', $url);
    $parts = explode('/', $url);

    krsort($parts);

    $line_array = null;
    $part_count = count($parts);

    foreach ($parts as $key => $value)
    {
        if ($line_array == null)
        {
            $line_array = array($value => $value);
        }
        else
        {
            $temp_array = $line_array;
            $line_array = array($value => $temp_array);
        }
    }

    $array = array_merge_recursive($array, $line_array);
}

print_r($array);

?>

答案 1 :(得分:0)

$urlArray = array(  'http://domain.com/a/a.jsp',
                    'http://domain.com/a/b/a.jsp',
                    'http://domain.com/a/b/b.jsp',
                    'http://domain.com/a/b/c.jsp',
                    'http://domain.com/a/c/1.jsp',
                    'http://domain.com/a/d/2.jsp',
                    'http://domain.com/a/d/a/2.jsp'
                 );

function testMapping($tree,$level,$value) {
    foreach($tree['value'] as $k => $val) {
        if (($val == $value) && ($tree['level'][$k] == $level)) {
            return true;
        }
    }
    return false;
}

$tree = array();
$i = 0;
foreach($urlArray as $url) {
    $parsed = parse_url($url);
    if ((!isset($tree['value'])) || (!in_array($parsed['host'],$tree['value']))) {
        $tree['value'][$i] = $parsed['host'];
        $tree['level'][$i++] = 0;
    }
    $path = explode('/',$parsed['path']);
    array_shift($path);
    $level = 1;
    foreach($path as $k => $node) {
        if (!testMapping($tree,$k+1,$node)) {
            $tree['value'][$i] = $node;
            $tree['level'][$i++] = $level;
        }
        $level++;
    }
}


echo '<pre>';
for ($i = 0; $i < count($tree['value']); $i++) {
    echo str_repeat(' ',$tree['level'][$i]*2);
    echo $tree['value'][$i];
    echo '<br />';
}
echo '</pre>';