Skip to content Skip to sidebar Skip to footer

Create Html List From Array With Levels

I have an array like this array(){ [0] => Object( lvl => 0, name ='1' ), [1] => Object( lvl => 1, name ='2' ),

Solution 1:

If you need list with ul, li tags, try to use this code. It should work.

$lastLvl = 1;
echo'<ul>';
foreach ($arrayas$object) {
    if ($object->lvl < $lastLvl) {
        for ($i = 1; $i <= ($lastLvl - $object->lvl); $i++)
            echo'</ul>';
    }

    if ($object->lvl > $lastLvl) {
        for ($i = 1; $i <= ($object->lvl - $lastLvl); $i++)
            echo'<ul>';
    }
    echo'<li>', $object->name, '</li>';

    $lastLvl = $object->lvl;
}
for ($i = 1; $i <= $lastLvl; $i++)
    echo'</ul>';

Solution 2:

What about something like this:

foreach ($arrayas$object) {
    echo'<p class="level', $object->lvl, '">', $object->name, '</p>';
}

You'll have to define classes (level1, level2, level3 ...) in CSS file then.

Or you can just use some sign for indention. Like this:

echo'<p>', str_repeat('-', $object->lvl), $object->name, '</p>';

Post a Comment for "Create Html List From Array With Levels"