PHP development classification technology uses recursion to achieve infinite classification (1)

First, we need to create a simple database test

Create a new table class and set 3 fields

Sort id int type.

Category name title varchar type.

Classification pid int type.

A table similar to the following:

111.png

Idea:

Define a custom function get_str, set the parent class pid = 0, use SQL The statement queries out its subclasses,Place the queried subclasses into $result

Use a while loop to get out the subclasses, and create an output pattern by constructing a string , call the custom function get_str, pass the id of the subclass into the custom function,

and then continue to query the next level.

'; while ($row = mysqli_fetch_array($result)) { //循环记录集 $str .= "
  • " . $row['id'] . "--" . $row['title'] . "
  • "; //构建字符串 get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 } $str .= ''; } return $str; } echo get_str(0); ?>

    The output is similar to:

    112.png

    Continuing Learning
    ||
    '; while ($row = mysqli_fetch_array($result)) { //循环记录集 $str .= "
  • " . $row['id'] . "--" . $row['title'] . "
  • "; //构建字符串 get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 } $str .= ''; } return $str; } echo get_str(0); ?>
    submit Reset Code
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!