I have a mysql table (menu) looking like this id (int) subid (int) name (varchar)
subid is 0 if it is top level menu point, and if it is sub, then it get the id from the one above
Data could be
1, 0, Top 1
2, 0, Top 2
3, 0, Top 3
4, 2, Sub 2,1
5, 2, Sub 2,2
6, 5, SubSub 2,2,1
7, 5, SubSub 2,2,2
8, 3, Sub 3,1
I want it to end up with a ul li list like this
<ul>
<li>Top 1</li>
<li>Top 2
<ul>
<li>Sub 2,1</li>
<li>Sub 2,2
<ul>
<li>SubSub 2,2,1</li>
<li>SubSub 2,2,2</li>
</ul>
</li>
</ul>
</li>
<li>Top 3
<ul>
<li>Sub 3,1</li>
</ul>
</li>
</ul>
I have found a recursive function, but it run a sql query per menupoint, and that can give memory problems on the server.
What will be the smartest way to make my menu? Should I select all data out in an Array first, or what to do? And if, how could I do that?
Looking forward to your answers - feel free to ask anything if I havent explained it good enough :)
get all data to array, next make from it 2 dimension array. At the end iterate through all items/keys.
something like this
<?php foreach( $array as $ul => $li ) {
if( $li['subid') != 0 ) {
foreach($li['child'] as $ul2 => $li2) {
echo '<li>' . $li2['name'] . '</li>';
}
} else {
echo '<li>' . $li['name'] . '</li>';
}
?>
You shouldn't have to connect for each item, just download the entire table into an array and then sort. The problem I've encountered is sub-menus : how do you distinguish them from top-links? The solution is add a 'parent' and 'hasChild' column to report the appropriate top link and 0 or 1 for hasChild, then call your recursive function with
function would look something like..
function myFunc(,$parent,$isSub){
//database stuff. I use PDO
while($arr = $stmt->fetch(PDO::FETCH_ASSOC)){
if($parent===$arr['parent']){
//make top links
if($arr['hasSub']===1 && $isSub===1){
//make subs
myFunc($arr,$arr['parent'],0)
}
}
}
}