Home  >  Article  >  Backend Development  >  How to achieve unlimited classification in php? Three unlimited classification methods in php

How to achieve unlimited classification in php? Three unlimited classification methods in php

青灯夜游
青灯夜游forward
2018-10-16 18:10:134250browse

This article will introduce to you how to achieve unlimited classification in PHP? Three unlimited classification methods in php. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Infinite classification means that starting from the highest classification, each sub-category can be divided into several sub-categories of its own, which can be divided all the time, which is called infinite classification;

The following is the classification Examples of Infinitus classification of provinces, cities and counties. The database is as shown in the figure:

The code example is as follows:


/**
 * @Description: 无限极分类一
 * @Author: Yang
 * @param $data  数据库数据
 * @param int $parent_id   父级ID
 * @return array
 */
function getTree1($data, $parent_id = 0)
{
    $tree = array();
    foreach ($data as $k => $v) {
        if ($v["parent_id"] == $parent_id) {
            unset($data[$k]);
            if (!empty($data)) {
                $children = getCategory($data, $v["id"]);
                if (!empty($children)) {
                    $v["_child"] = $children;
                }
            }
            $tree[] = $v;
        }
    }
    return $tree;
}


/**
 * @Description: 无限极分类二
 * @Author: Yang
 * @param $data   数据库数据
 * @param int $parent_id  父级ID
 * @param int $level  等级
 * @return array
 */
function getTree2($data, $parent_id = 0, $level = 0)
{
    static $tree = array();
    foreach ($data as $k => $v) {
        if ($v["parent_id"] == $parent_id) {
            $v["level"] = $level;
            $tree[] = $v;
            getTree($data, $v["id"], $level + 1);
        }
    }
    return $tree;
}

/**
 * @Description: 无限分类三:面包屑导航
 * @Author: Yang
 * @param $data  数据库数据
 * @param $id    分类ID
 * @return array
 */
function getCrumbsBar($data, $id) {
    static $tree = array();
    foreach ($data as $k => $v) {
        if ($v["id"] == $id) {
            getCrumbsBar($data, $v["parent_id"]);
            $tree[] = $v;
        }
    }
    return $tree;
}

The above is the entire content of this article, more related For tutorials, please visit php programming from entry to mastering a full set of video tutorials, php practical video tutorial, bootstrap video tutorial!

The above is the detailed content of How to achieve unlimited classification in php? Three unlimited classification methods in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete