Home > Database > Mysql Tutorial > How to Build an Unordered List Menu Tree in PHP/MySQL Without Recursion?

How to Build an Unordered List Menu Tree in PHP/MySQL Without Recursion?

Patricia Arquette
Release: 2024-11-03 19:24:29
Original
899 people have browsed it

How to Build an Unordered List Menu Tree in PHP/MySQL Without Recursion?

PHP/MySQL Unordered List Menu Tree Construction: A Non-Recursive Single Database Query Approach

Building unordered list menu trees from database queries is a common task. Typically, recursive functions that query the database multiple times are employed. However, a more efficient non-recursive approach is possible using a single database query.

Given an array of page objects with id, title, and parent_id attributes, the goal is to create a function that generates the HTML for an unordered list menu.

Solution:

Our solution employs the following steps:

  1. Create a helper function, has_children, to determine if a given parent_id has any children in the array.
  2. Implement a build_menu function that iterates through the page objects and constructs the menu list recursively.
  3. Call build_menu with the initial parent ID of 0 to create the root of the menu tree.

Code:

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

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>
Copy after login

Example Usage:

<code class="php">$menu = [
  ['id' => 1, 'title' => 'Menu 1', 'parent_id' => null],
  ... // Additional menu objects
];

echo build_menu($menu); // Outputs the complete menu list</code>
Copy after login

Advantages:

  • Non-recursive approach eliminates the risk of stack overflow.
  • Single database query ensures efficient data retrieval.
  • Modular design facilitates maintainability and reusability.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template