Home  >  Article  >  Backend Development  >  How to implement Infinitus classification in PHP?

How to implement Infinitus classification in PHP?

韦小宝
韦小宝Original
2017-11-15 16:30:241496browse

Each infinite category needs to record its parent id. When it is a top-level category, the parent id is 0. In this way, no matter which category it is, it can be checked layer by layer through the parent id. Indicate all its parents so that you can clearly know which category it belongs to and the depth of the hierarchy. Unlimited Category is very commonly used in actual development, and Unlimited Category is also often used in interviews. Asked

include PHP
/*
使用的是三种递归中的一种 &
/*
include('Catecontroller.php');//引入连接数据库文件

function getList($pid = 0, &$result = array(), $spac = 0)
{
    $spac = $spac + 2;//标题前空格重复的次数
    $sql = "SELECT * FROM cate WHERE pid= $pid";//根据父id查找数据
    $res = mysql_query($sql);//发送sql语句

    while ($row = mysql_fetch_assoc($res)) {//判断$row里的值是否为空然后再循环
        $row['cate_name'] = str_repeat(' ',$spac).'|--'.$row['cate_name']; //str_repeat 重复括号里的字符串,后面跟的是次数
        $result[] = $row;//把数组赋给 $result
        getList($row['id'],$result,$spac);//递归调用,自己调用自己 这个括号里的参数和上面getList($pid=0...)是一样的$row['id']==$pid=0;
    }
    return $result;//把结果返回出去
}

$rs = getList();//使用方法

var_dump($rs);//打印方法结果

The above infinite classification uses a recursive algorithm. The simple explanation of the recursive algorithm is to call itself.

Related recommendations:

php unlimited classification tree [supports sub-category sorting]

php method of recursively traversing multi-dimensional arrays

php recursive function call explanation

The above is the detailed content of How to implement Infinitus classification in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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