php Loops and recursions play an important role in the PHP development process. This article will explain its related knowledge.
php realizes infinite levels of classification through loops and recursions
First use loops to achieve simple level display
//Use PDO to connect to the database
<!--?php header("content-type:text/html;charset=utf-8"); $pdo = new PDO("mysql:host=127.0.0.1;dbname=ninthexam","root","root"); $rs = $pdo ---> query("select * from city"); while($row = $rs -> fetch()){ $data[] = $row; } //循环实现分类 foreach($data as $k=>$v) { if($v['parint_id'] == 0) { $tmp[] = $v; foreach($data as $key=>$value) { if($v['city_id'] == $value['parint_id']) { $tmp[] = $value; } } } } echo " "; print_r($tmp);
//Use recursion to achieve infinite classification display
//Use recursion Realizing infinite classification
function digui($data,$parint_id = 0 ,$cengji = 0) { //使用静态定义 static $tmp = array(); foreach($data as $k=>$v) { //判断如果“层级ID==自增ID” if($v['parint_id'] == $parint_id) { $v['cengji'] = $cengji; $tmp[] = $v; digui($data,$v['city_id'],$cengji+1); } } return $tmp; } print_r(digui($data,$parint_id = 0 ,$cengji = 0));
The above are several ways to realize simple infinite classification.
This article explains the related operations of PHP loop and recursion to achieve infinite classification. For more related knowledge, please pay attention to the PHP Chinese website.
Related recommendations:
Use the magic method __CLASS__ in PHP to obtain related operations of the class name
How to obtain the openid and basic information of WeChat users through PHP
php code implements 12306 remaining ticket query and price query functions
The above is the detailed content of How to achieve infinite level classification through php loop and recursion. For more information, please follow other related articles on the PHP Chinese website!