1

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);
}
  1. Any ideas how to efficiently write something like this?
  2. Or should I consider updating the way it's stored in the DB?
  3. If I must update the way it's stored, what must I update it to?

Thanks!

rockstardev
  • 13,479
  • 39
  • 164
  • 296
  • 1
    The function should have parameter $parent (e.g.) which would store the data from DB. Then if the PARENT column is not empty you would call again the function. This is the idea. The way you are storing the data is OK – DeiForm Jul 26 '13 at 14:56
  • @deceze link is a pretty good example on how to archive this. – Prix Jul 26 '13 at 15:08

0 Answers0