-2

I have created a MySQL database table where I want to show the menu structure based on their parent. The menu table contains the following data:

id | menuname          | parentid
---+-------------------+---------
 1 | dashboard         |        0
 2 | Content           |        0
 3 | Home Page Content |        2
 4 | Banners           |        2
 5 | Settings          |        0
 6 | Block Content     |        3
 7 | Site Content      |        3

So that the menu structure will look like:

  • dashboard
  • Content
    • Home Page Content
      • Block Content
      • Site Content
  • Banners
  • Settings

I have gone though the post over here Recursive menu tree from array however, unable to understand the basics. However, the idea I understood that I need to write a recursive function to sort out this. Can someone give me some ideas how to generate the above?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • For starters you should use `select * from my_table order by parentid ASC, id ASC` and the rest will need to be PHP logic. Also, why isn't `Banners` a child of `Content` in your example? If you are interested in hierarchical table structures and queries in MySQL then you can check out https://stackoverflow.com/q/20215744/2191572 – MonkeyZeus May 17 '18 at 12:24

1 Answers1

0

Imagine you are selected from database with sql query

SELECT * FROM my_table ORDER BY parentid ASC, id ASC

and you have this array in PHP

$arr = [

    [
        "id"=>1,
        "username"=>"dashboard",
        "parentid"=>0
    ],
    [
        "id"=>2,
        "username"=>"dashboard",
        "parentid"=>0
    ],
    [
        "id"=>5,
        "username"=>"dashboard",
        "parentid"=>0
    ],
    [
        "id"=>3,
        "username"=>"dashboard",
        "parentid"=>2
    ],
    [
        "id"=>4,
        "username"=>"dashboard",
        "parentid"=>2
    ],
    [
        "id"=>6,
        "username"=>"dashboard",
        "parentid"=>3
    ],
    [
        "id"=>7,
        "username"=>"dashboard",
        "parentid"=>3
    ],

];

$categories = [];
    foreach ($arr as $item){
        if($item["parentid"]==0){
            $categories[$item["id"]] = $item;
        }else{
            $categories[$item["parentid"]]["subs"][] = $item;
        }
    }
Davit Huroyan
  • 302
  • 4
  • 16