开发者

How to display a side nav menu with many sub-categories using PHP and MySQL?

开发者 https://www.devze.com 2022-12-09 14:28 出处:网络
Okay I was wondering how can you use PHP and MySQL to create and display a side nav menu with many categories and sub-categories?

Okay I was wondering how can you use PHP and MySQL to create and display a side nav menu with many categories and sub-categories?

I just don't know where to begin coding the PHP code?

<ul>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a>
      <ul>
        <li><a href="" title="">Second Nested Link</a></li>
        <li><a href="" title="">Second Nested Link</a></li>
        <li><a href="" title="">Second Nested Link</a>
          <ul>
            <li><a href="" title="">Third Nested Link</a></li>
            <li><a href="" title="">Third Nested Link</a></li>
            <li><a href="" title="">Third Nested Link</a>
              <ul>
                <li><a href="" title="">Fourth Nested Link</a></li>
                <li><a href="" title="">Fourth Nested Link</a></li>
                <li><a href="" title="">Fourth Nested Link</a></li>
              </ul>
            </li>
            <li><a href="" title="">Third Nested Link</a></li>
            <li><a href="" title="">Third Nested Link</a></li>
          </ul>
        </li>
        <li><a href="" title="">Second Nested Link</a></li>
        <li><a href="" title="">Second Nested Link</a></li>
      </ul开发者_StackOverflow中文版>
   </li>
   <li><a href="" title="">First Nested Link</a></li>
   <li><a href="" title="">First Nested Link</a></li>
</ul>

Here is my MySQL tables.

* categories
      id | category_name | description
* sub_categories
      id | parent_id | category_name | description


You should only need one table for your categories; just set the parent_id field to null for top-level categories.

As for actually generating the HTML, you can do something along these lines (pseudocode), where $category_data is the results of the query in a two-dimensional array and $category_id is the id of the parent category being generated. To kick it off, use $category_id = 0

function print_category($category_data, $category_id)
{
    print "<ul>";
    foreach ($category_data as $category)
    {
        if ((integer)$category['parent_id'] == $category_id)
        {
            print "<li>" . $category['category_name'] . "</li>";
            print_category($category_data, $category['id']);
        }
    }
    print "</ul>";
}

You'll have to modify that for your own layout and table structure. You can improve the performance (if you have a huge number of categories) by transforming the array into a three-dimensional array, $category_data[parent_id][id][category_row].

0

精彩评论

暂无评论...
验证码 换一张
取 消