Help with N-level Tree Structure Menu for Custom LMS using php/mysql

Can any body please help me with indexing of parent-child Hierarchy Menu like

Basically, iam creating a personal lms.

Main (K-12,NCERT)
->Class (Class 3,Class 4,Class 5)
->Subject (Physics,Chemistry)
->Units (Unit 1,Unit 2)
->Chapter (Chap 1, Chap 2)
->Topic (Topic 1, Topic 2)
->Sub Topic (Sub Top 1, Sub Top 2)
->Sub Sub Topic (Sub Sub Top 1, Sub Sub Top 2)

every topic have its own title and contents


NCERT
Class 5
Class 6
Physics
Unit 4
Chapter 1
Chapter 2
Topic 1
Topic 2
Topic 3
Sub Topic 1
Topic 4
Chapter 3
Unit 5
Chemistry
Biology
Class 7
Class 8
Physics
Unit 1
Chemistry
Biology
Unit 4
Unit 5


1
2
3
3.1
3.1.1
3.1.1.1
3.1.1.1.1
3.2
3.3
4
5


n

Thanks
Seyed

How are you storing this data in the database?

Menu
cat_id
parent_id
cat_name

Content
content_id
cat_id ( from the menu table)
content
swf_path
active

I don’t understand , how to add the menu and its corresponding contents ? If its around 50 records no problem, we can use drop down. i may have 1000+ menu items and contents respectively.

Also certain cat_name is common (i.e, Physics, Chemistry… Unit 1,2)

So a parent-child heirarchy. (This is always the fun part of MySQL. Hierarchical constructions.)


 $res = $db->query("SELECT cat_id,cat_name,parent_id FROM categories ORDER BY cat_id");
 $rows = $res->fetch_all();
 echo build_children(0,$rows);

function build_children($parent,$data) {
	$matches = array_filter($data, function($a) use($parent)  {
		return $a['parent_id'] === $parent;
	});
        $out = "";
	foreach($matches AS $match) {
		$out .= "<ul><li><a href='content.php?id=".$match['cat_id']."'>".$match['cat_name']."</a></li>";
		$out .= build_children($match['cat_id'],$data);
		$out .= "</ul>";
	}
        return $out;
}

EDIT: To conform with the normal procedure of a function not echo’ing directly, i’ve put the output into a return.
EDIT2: If your top level entries dont have a root that you want displayed, change the 0 in the original function call to null.