0

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?

3

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.