Tim Döring
Tim Döring

Reputation: 41

Create a menu list dynamically from php array with subelements

I have a PHP array with menu items and submenu items. The submenu items are set with a parent ID and depth. An example array looks like this:

[0] => stdClass Object ( [CategoryID] => 4 [ParentCategoryID] => -1 [Depth] => 1 [Name] => Menu1
[1] => stdClass Object ( [CategoryID] => 2 [ParentCategoryID] => 4 [Depth] => 2 [Name] => Submenu1 
[2] => stdClass Object ( [CategoryID] => 3 [ParentCategoryID] => 4 [Depth] => 2 [Name] => Submenu2 
[3] => stdClass Object ( [CategoryID] => 1 [ParentCategoryID] => -1 [Depth] => 1 [Name] => Menu2

Now I want to have the array output as a list and sublist like this:

<ul>
    <li>
        Menu1
        <ul>
            <li>Submenu1</li>
            <li>Submenu2</li>
        <ul>
    </li>
    <li>
        Menu2
    </li>
<ul>

I was not able to get those submenus to the parent element. Is there any way to do this in an easy way?

Upvotes: 0

Views: 436

Answers (1)

Rahul
Rahul

Reputation: 18577

You can loop your array $a like this,

echo "<ul>";
foreach ($a as $k => $v) {
    // assuming depth = 1 is only for parent categories
    if ($v->Depth == 1) {
        echo "<li>";
        echo $v->Name;
        echo "<ul>";
        foreach ($a as $k1 => $v1) {
            // checking inner loops parent category with outer loop's category id
            if ($v1->ParentCategoryID == $v->CategoryID) { 
                echo "<li>";
                echo $v1->Name;
                echo "</li>";
            }
        }
        echo "</ul>";
        echo "</li>";
    }
}
echo "</ul>";

Try running in PHP script.

Upvotes: 1

Related Questions