1

Alright, it's hump day, and my brain's already shot.

Can someone tell me what I'm doing wrong here, I'm trying to build a Navigation list properly (hierarchal)

Here's the array:

Array
(
[0] => Array
    (
        [contentID] => 1
        [parentID] => 0
        [LinkAlias] => 
    )

[1] => Array
    (
        [contentID] => 2
        [parentID] => 0
        [LinkAlias] => inner
    )

[2] => Array
    (
        [contentID] => 3
        [parentID] => 2
        [LinkAlias] => inner-2
    )

[3] => Array
    (
        [contentID] => 4
        [parentID] => 3
        [LinkAlias] => inner-21
    )

)

And my attempts at the recursive function:

    // Parse out the array for displaying a multi-level menu
    private function ParseMenu($menu, $parent = 0){
        $ret .= '<ul>';
        $iCt = count($menu);


        for($i=0; $i < $iCt; ++$i){
            if($menu[$i]['parentID'] == $parent){               
                $ret .= '   <li>' . $menu[$i]['LinkAlias'];
                if($parent > 0){
                    $ret .= ParseMenu($menu, $menu[$i]['contentID']);
                }
                $ret .= '</li>';                
            }
        }
        $ret .= '</ul>';
        return $ret;
    }

Right now, all it is returning:

<ul>
    <li></li>
    <li>inner</li>
</ul>

It should be showing

<ul>
    <li></li><!-- yes this is intentional -->
    <li>inner
            <ul>
                    <li>inner-2
                            <ul>
                                    <li>inner-21</li>
                            </ul>
                    </li>
            </ul>
</ul>

So.. what am I doing wrong, and how can I fix it?

1 Answer 1

3

Make this line ...

if($parent > 0){
    $ret .= ParseMenu($menu, $menu[$i]['contentID']);
}

into ...

$ret .= $this->ParseMenu($menu, $menu[$i]['contentID']);

You are never calling your function again because you are always starting with $parent = 0

$ret .= '</ul>';
if($ret == '<ul></ul>'){ 
    return;
} else {
    return $ret;
}
Sign up to request clarification or add additional context in comments.

3 Comments

what a tool I am... told you... brain is shot. It works, this is inside a function, so I have to $this->ParseMenu it... Few more tests and I'll accept. Thanks~
i have updated my code, you are working in a class so you will need $this->
:) yeah. Works good. Now the only thing left is to get rid of the extra <ul></ul> when there are no children

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.