Jarno van Rhijn
Jarno van Rhijn

Reputation: 126

PHP Recursive navigation

So i have this issue regarding recursive arrays. What i want is to get an recursive array with PHP from my database so that i can create a navigation menu with submenu's without creating another table.

this is the function i have so far;

function getMenu($tree = null){
        $tree2 = array();
        $tree = getPages();
        foreach($tree as $i => $item){
            if($item->parent_id == $item->ID){
                $tree2[$item->ID] = $item;
                $tree2[$item->ID]['submenu'] = getMenu($tree, $item->ID);
            }
        }

        return $tree2;
    }

To make things clear i did not create this function myself but got it from http://www.jugbit.com/php/php-recursive-menu-with-1-query/ and made adjustments where i thought where the right one

The $tree variable is coming from this function;

function getPages($limit = null,$sort = null) {
     global $db;
     $query = $db->prepare('SELECT * FROM pages ORDER BY Position');
     $query->execute();
     return $query->fetchAll(PDO::FETCH_CLASS);
}

Now i have been busting my balls over this for the last two days trying to figure out what i am doing wrong.

if i print the getMenu function all i get is an empty array wich i can't figure out why. it does get the foreach right and i don't think that's the issue but i'm not 100% sure..

i hope the question is clear but if it's not i'm sorry and will clarify where needed.

Thanks in advance

Upvotes: 0

Views: 514

Answers (2)

Neville Kuyt
Neville Kuyt

Reputation: 29649

There are a whole bunch of problems with your code...

Firstly, you use a variable named $tree in 3 different ways, and I'm pretty sure you're overwriting the content of that variable without meaning to.

$tree is a parameter to your function, it's then overwritten in the line $tree = getPages(); - so whatever parameter was passed in is gone. You then use it as the iterator in the line foreach($tree as $i => $item) - so again, whatever was in there got overwritten again.

See what happens if you fix that.

Secondly, your SQL statement retrieves the entire "pages" table, not the children of the current page.

Thirdly, when you recurse, you pass in a second parameter, but there's no placeholder for that in the function declaration, so the parameter disappears into thin air.

Upvotes: 1

Supericy
Supericy

Reputation: 5896

In getPages, if you want it to return an associative array, then you need to do:

return $query->fetchAll(PDO::FETCH_ASSOC);

and then your getMenu would look like:

function getMenu($tree = null, $parent = 0) {
    if (!isset($tree))
        $tree = getPages();

    $tree2 = array();
    foreach($tree as $i => $item) {
        if($item['id'] == $parent) {
            $tree2[$item['id']] = $item;
            $tree2[$item['id']]['submenu'] = getMenu($tree, $item['id']);
        }
    }

    return $tree2;
}

Upvotes: 3

Related Questions