多维数组到HTML无序列表

时间:2014-07-21 13:05:29

标签: php html arrays multidimensional-array

我有以下数组,我想将其转换为无序列表(HTML)。

Array
(
    [0] => Array
        (
            [url] => /
            [id] => 53a8717fe9ab5
            [template] => home
            [title] => Home
        )

    [1] => Array
        (
            [url] => /about
            [id] => 53a871fe8b05b
            [template] => content
            [title] => About
        )

    [2] => Array
        (
            [url] => /about/sub
            [id] => 53cb88b7ed22d
            [template] => content
            [title] => About (sub)
        )

    [3] => Array
        (
            [url] => /about/sub/subsub
            [id] => 53cb88bc7d32d
            [template] => content
            [title] => About (subsub)
        )

    [4] => Array
        (
            [url] => /contact
            [id] => 53a8718981161
            [template] => content
            [title] => Contact us
        )

)

所以我试图从上面的那个创建一个多维数组,如下所示:

Array
(
    [0] => /
    [1] => /about
    [about] => Array
        (
            [0] => /about/sub
            [sub] => Array
                (
                    [0] => /about/sub/subsub
                )

        )

    [2] => /contact
)

但就我而言......更不用说创建实际的<ul>

非常感谢任何帮助。

修改

我使用:

生成了递归<ul>
private function generateTree($from) {
    $to = [];

    foreach ( $from as $element ) {
        $path = explode('/', $element["url"]);
        if ( count($path) === 1 ) array_unshift($path, '/');

        $_to = &$to;
        for ( $i = 0; $i < count($path)-1; $i++ ) {
            if ( !array_key_exists($path[$i], $_to) ) $_to[$path[$i]] = [];
            $_to = &$_to[$path[$i]];
            print_r ( implode("/", $path));
            echo "<br>";
        }
        $_to[] = $element["url"];
    }

    return $to[""];
}

这是我的预期输出:

<ul>
    <li><a href="/">Home</a></li>
    <li>
        <a href="/about">About</a>
        <ul>
            <li>
                <a href="/about/sub">About (sub)</a>
                <ul>
                    <li><a href="/about/sub/subsub">About (subsub)</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="/contact">Contact</a></li>
</ul>

1 个答案:

答案 0 :(得分:4)

尝试这样的功能:

function ToUl($input){
   echo "<ul>";

   $oldvalue = null;
   foreach($input as $value){
     if($oldvalue != null && !is_array($value))
        echo "</li>";
     if(is_array($value)){
        ToUl($value);
     }else
        echo "<li>" + $value;
      $oldvalue = $value;
    }

    if($oldvalue != null)
      echo "</li>";

   echo "</ul>";
}

<强> [编辑]

我将保留为每个数组创建li的函数,这样更简单,以防任何读者需要它:

function ToUl($input){
   echo "<ul>";

   foreach($input as $value)
     if(is_array($value)){
        echo "<li>";
        ToUl($value);
        echo "</li>";
     }else
        echo "<li>" + $value + "</li>";

   echo "</ul>";
}