PHP development classification technology uses recursion to achieve infinite classification (1)
First, we need to create a simple database test
<?php $link = mysqli_connect('localhost','username','password','test'); mysqli_set_charset($link, "utf8"); if (!$link) { die("连接失败:".mysqli_connect_error()); } ?>
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:
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.
<?php function get_str($id = 0) { global $str; global $link; //global 关键词用于访问函数内的全局变量。 $sql = "select id,title from class where pid= $id"; $result = mysqli_query($link,$sql);//查询pid的子类的分类 if($result){//如果有子类 $str .= '<ul>'; while ($row = mysqli_fetch_array($result)) { //循环记录集 $str .= "<li>" . $row['id'] . "--" . $row['title'] . "</li>"; //构建字符串 get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 } $str .= '</ul>'; } return $str; } echo get_str(0); ?>
The output is similar to: