-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?

1
  • 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 stackoverflow.com/q/20215744/2191572 Commented May 17, 2018 at 12:24

1 Answer 1

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;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.