I work on this issue since yesterday. More specifically - I have some values in the database, which look as follows:
___开发者_如何转开发_________________________________ | id | parentId | name | url | ------------------------------------ | 1 | 0 | Nieuws | url_1 | ------------------------------------ | 2 | 0 | Reviews | url_2 | ------------------------------------ | 3 | 0 | Meuk | url_3 | ------------------------------------ | 4 | 1 | Games | url_4 | ------------------------------------ | 5 | 1 | Internet | url_5 | ------------------------------------ | 6 | 5 | Browsers | url_6 | ------------------------------------
I would like to see generated tree on the basis of these values. Target shape should look like this:
<ul>
<li><a href="url_1">Nieuws</a>
<ul>
<li><a href="url_1/url_4">Games</a></li>
<li><a href="url_1/url_5">Internet</a>
<ul>
<li><a href="url_1/url_5/url_6">Browsers</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="url_2">Reviews</a></li>
<li><a href="url_3">Meuk</a></li>
</ul>
It's important for me to have all the slashes inside the tree (full path with all the parents & children).
I would like to add, that I found the code on this page: http://crisp.tweakblogs.net/blog/317/formatting-a-multi-level-menu-using-only-one-query.html but I can not redo it in such a manner as described above. I'll be very grateful for any help, because the application deadline is approaching very fast :(
Only one modification. I think this way is much simpler. Instead of using an array to store the URL, I pass a string as an argument (containing the base url).
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData, $urlRoot)
{
$html = '';
if (isset($menuData['parents'][$parentId]))
{
$html = '<ul>';
foreach ($menuData['parents'][$parentId] as $itemId)
{
$url = $urlRoot . $itemId['url'] . '/';
$html .= '<li><a href="$url">' . $menuData['items'][$itemId]['name'] . '</a>';
// find childitems recursively
$html .= buildMenu($itemId, $menuData, $url);
$html .= '</li>';
}
$html .= '</ul>';
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData, '');
based on the function in your link, if you add url to the query, something like this should work:
<?php
// menu builder function, parentId 0 is the root
function buildMenu($parentId, $menuData, $nodes=false)
{
$html = '';
if (isset($menuData['parents'][$parentId]))
{
$html = '<ul>';
if($nodes === false){
$nodes = array();
} elseif(!is_array($nodes)) {
$nodes = array($nodes);
} else {
$nodes[] = $menuData['items'][$parentId]['url'];
}
foreach ($menuData['parents'][$parentId] as $itemId)
{
$html .= '<li><a href="/' . implode('/', $nodes) . '">';
$html .= $menuData['items'][$itemId]['name'] . '</a>';
// find childitems recursively
$html .= buildMenu($itemId, $menuData, $nodes);
$html .= '</li>';
}
$html .= '</ul>';
array_pop($nodes);
}
return $html;
}
// output the menu
echo buildMenu(0, $menuData);
?>
精彩评论