Home >Backend Development >PHP Tutorial >3 ways to implement unlimited classification in PHP (summary)

3 ways to implement unlimited classification in PHP (summary)

不言
不言forward
2018-10-15 14:28:012109browse

This article brings you three implementation methods (summary) of unlimited classification 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 detailed content of 3 ways to implement unlimited classification in PHP (summary). 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