recursive function category database

后端 未结 4 1912
春和景丽
春和景丽 2021-01-06 16:57

i hoping to create a recursive function which i don\'t have an idea yet

this is my code to fetch category from database

  

        
相关标签:
4条回答
  • 2021-01-06 17:35

    Something like this?

    function getCategories($mid, $categoryParent = 1)
    {
        $return = '';
        $results = mysql_query("SELECT * FROM categories WHERE category_parent = '$categoryParent' ORDER BY lft ASC", $mid);
        while($row = mysql_fetch_array($results)) {
            $return .= "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a></li>";
            $subs = getCategories($mid, $row['category_id']);
            if (!empty($subs)) {
                $return .= '<ul>';
                $return .= $subs;
                $return .= '<ul>';
            }
        }
        return $return;
    }
    
    $mid = mysql_connect($host, $user, $pass);
    echo getCategories($mid);
    

    Would print out all your categories, of course fix it to exactly how you want, but that should give you an idea of how recursive functions could work

    0 讨论(0)
  • 2021-01-06 17:38

    What you need to do, is build a recursive function. That is, a function that calls itself within. An example:

    function getCategories($parent=0) {
        $res = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY left ASC");
        if (mysql_num_rows($res) > 0) {
            $category = mysql_fetch_object();
            echo '<ul>';
            echo '<li><a href="' . $category->category_safe_name . '">' . $category->category_name . '</a>';
            getCategories($category->category_id);
            echo '</li>';
        }
    }
    

    If I've made any typos in regards to table and column names then obviously swap them out for the correct values.

    0 讨论(0)
  • 2021-01-06 17:39

    You should have a look at Managing Hierarchical Data in MySQL.

    It gives a good overview of some approaches to using hierarchical data in MySQL.

    0 讨论(0)
  • 2021-01-06 17:45

    I would do :

    <?php
    function getChildren($id=1) {
      $sql = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY lft ASC");
      echo "<ul>";
      while($row = mysql_fetch_array($sql)) {
        echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>";
        getChildren($row['category_id']);
        echo "</li>";
      }
      echo "</ul>";
    }
    
    getChildren();
    ?>
    
    0 讨论(0)
提交回复
热议问题