简体   繁体   中英

PHP Build Tree with ul tag

I have the following php array

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
        )

    [2] => Array
        (
            [0] => 4
        )

    [4] => Array
        (
            [0] => 5
        )

)

In which the first keys ( 0 , 1 , 2 , 4 ) are the IDs that contains childrens.

Everything starts from the key 0 which is the parent for all the others.

I want to build a tree using ul li tags from this array. I searched the site i found similar topics but then i noticed my method isn't the same.

I tried to do it and failed.

EDIT

This is what i have so far:

function PrintTree( $arr )
{
    global $names;

    echo "<ul>";
    foreach ( $arr as $key => $childrens )
    {
        if ( $key == 0 and is_array( $childrens ) )
        {
            PrintTree( $childrens );
            continue;
        }

        if ( is_array( $childrens ) )
        {
            echo "<li><a href=\"#\">" . $names[$key] . "</a>";
            PrintTree( $childrens );
            echo "</li>";
        }
        else
        {
            echo "<li><a href=\"#\">" . $names[$childrens] . "</a></li>";
        }
    }
    echo "</ul>";
}

The above code fails and produces this:

Root 
      Item 1
      Item 2
   Item 1
      Item 3
   Item 2
      Item 4
   Item 4
      Item 5

But the correct tree should be:

Root 
     Item 1
         Item 3
     Item 2
         Item 4
             Item 5

Thank you

Perhaps something like this snippet should work :

$foo = [
    0 => [1,2],
    1 => [3],
    2 => [4],
    4 => [5],
];

function track($array, $index = 0) {
    $out = '<ul>';
    if (isset($array[$index]) && is_array($array[$index])) {
        foreach($array[$index] as $track) {
            $out .= '<li>'.$track;
            $out .= track($array, $track);
            $out .= '</li>';
        }
    }
    $out .= '</ul>';
    return $out;
}

echo track($foo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM