How to achieve infinite level classification through php loop and recursion

jacklove
Release: 2023-03-30 18:44:02
Original
2140 people have browsed it

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[&#39;parint_id&#39;] == 0)
    {
        $tmp[] = $v;
        foreach($data as $key=>$value)
        {
            if($v[&#39;city_id&#39;] == $value[&#39;parint_id&#39;])
            {
                $tmp[] = $value;
            }
        }
    }
}
echo "
"; print_r($tmp);
Copy after login

//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[&#39;parint_id&#39;] == $parint_id)
               {
                   $v[&#39;cengji&#39;] = $cengji;
                   $tmp[] = $v;
                   digui($data,$v[&#39;city_id&#39;],$cengji+1);
               }
           }
           return $tmp;
       }
print_r(digui($data,$parint_id = 0 ,$cengji = 0));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template