Home > Article > Backend Development > PHP+mysql does not use recursion to achieve infinite classification examples (non-recursive), mysql recursion_PHP tutorial
To achieve infinite classification, recursion is generally the first and easiest thing to think of, but recursion is generally considered a resource-consuming method, so many systems do not consider using recursion
This article is still implemented through the design of the database and a SQL statement
The database fields are roughly as follows:
You can assume the following data:
Unlimited classification operation code:
<?php $sql=”SELECT * FROM tree order by path”; $result=$nbs->Query($sql); while($rows=$nbs->fetch_array($result)){ if(substr_count($rows['path'],',')>2){ for($i=0;$i<(substr_count($rows['path'],',')-2);$i++) echo ‘ ‘; } echo $rows['class_name'].'<br>'; } ?> $conn = mysql_connect ( 'localhost', 'root', 'root' ); mysql_select_db ( 'wanggou123', $conn ); mysql_query ( 'set names UTF8' ); $sql = "select id,concat(catpath,'-',id) as abspath,name from category order by abspath"; $query = mysql_query ( $sql ); while ( $row=mysql_fetch_array($query)) { /** * 第一种展示方法 */ /*$space = str_repeat ( ' ', count ( explode ( '-', $row ['abspath'] ) ) - 1 ); echo $space . $row ['name'] . ' ';*/ /** 第二种展示方法 */ $space = str_repeat ( '——', count ( explode ( '-', $row ['abspath'] ) ) - 1 ); $option .= '' . $space . $row ['name'] . '<Br>'; } echo $option; exit(); echo '<select name="opt">' . $option . '</select>';
Where $nbs is the database operation class, this method is simple and clear!
First decode json into an array, use the json_decode function. Note that you must add the second parameter, otherwise it will return an object. The next step is recursion. This is the simplest recursion that just needs to be traversed one by one.
The following is the complete code:
$data= json_decode($str,true);$options = getChildren($data);function getChildren($parent,$deep=0) {foreach($parent as $ row) {$data[] = array("id"=>$row['id'], "name"=>$row['name'],"pid"=>$row['parentid' ],'deep'=>$deep);if ($row['childs']) {$data = array_merge($data, getChildren($row['childs'], $deep+1));}} return $data;}?>701d81aaa14b8afd38d7545721c937f255a5f5bd5294290d7b34eac948d750689e4db9ea3aa010dc459f635bb13c1f73">98830ae643c695729d3a60a03343c488dd85fc2ea014f2ee02cc4cad3669d5e14afa15d3069109ac30911f04c56f33384219f431c5ecc1a046160e9df8d78b1218bb6ffaf0152bbe49cd8a3620346341
The above code has been tested and passed. The rendering is as follows
Foreach itself is equivalent to judgment. When the $arr array is not empty, foreach will traverse and recursively access the child nodes. However, for leaf nodes, the $arr array is empty and will not be foreached at all. At this time, it is directly returned. clear?