Home  >  Article  >  Database  >  How to Create a Tree Menu in PHP/MySQL Without Recursion?

How to Create a Tree Menu in PHP/MySQL Without Recursion?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 20:45:02895browse

How to Create a Tree Menu in PHP/MySQL Without Recursion?

PHP / MySQL Build Tree Menu without Recursion

Background:

Building a tree menu from database data can be a common task. This article explores how to construct an unordered list (UL) menu tree from a PHP array of page objects without using recursion.

Data Setup:

Your page objects have the following attributes:

  • id
  • title
  • parent_id (set to null for root pages)

Function Overview:

We'll create a function that takes an array of page objects and generates the corresponding HTML UL tree.

Helper Function: has_children()

This function checks if a page has child pages.

<code class="php">function has_children($rows, $id) {
  foreach ($rows as $row) {
    if ($row['parent_id'] == $id)
      return true;
  }
  return false;
}</code>

Recursive Build_Menu() Function

The build_menu() function iterates through the array and generates the HTML UL tree. It uses a variable $parent to keep track of the current parent page.

<code class="php">function build_menu($rows, $parent=0)
{  
  $result = "<ul>";
  foreach ($rows as $row)
  {
    if ($row['parent_id'] == $parent){
      $result.= "<li>{$row['title']}";
      if (has_children($rows,$row['id']))
        $result.= build_menu($rows,$row['id']);
      $result.= "</li>";
    }
  }
  $result.= "</ul>";

  return $result;
}</code>

Output:

After passing the array of page objects to the build_menu() function, you can echo the resulting HTML UL tree. The output will be a nested UL menu structure representing your database data.

<code class="php">echo build_menu($menu);</code>

The above is the detailed content of How to Create a Tree Menu in PHP/MySQL Without Recursion?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn