I have the following table which I grab from the database and get back as a standard array in PHP.
ID | PARENT | Title
1 | null | MAIN
2 | 1 | SubCat1
3 | 2 | Menu Item 1.1
4 | 2 | Menu Item 1.2
5 | 1 | SubCat2
6 | 5 | Menu Item 2.1
7 | 5 | Menu Item 2.2
8 | null | MAIN2
I want to end up with an array like this:
MAIN
SubCat1
Menu Item 1.1
Menu Item 1.2
SubCat2
Menu Item 2.1
Menu Item 2.2
MAIN2
It must be albe to support even deeper levels. How can I write a recursive function that will return it in this structure. So far I have:
$menu = buildFromData($rows);
private function buildFromData(&$rows, &$result, $parent = null) {
$unsorted = array();
foreach ($rows as $r) {
if ($r->parent == $parent) $result[] = $r;
else $unsorted[] = $r;
}
$rows = $unsorted;
$this->buildFromData($rows, $result, 1);
}
- Any ideas how to efficiently write something like this?
- Or should I consider updating the way it's stored in the DB?
- If I must update the way it's stored, what must I update it to?
Thanks!