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;}?>
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?