search
HomeBackend DevelopmentPHP TutorialPHP Category class library unlimited categories

PHP Category class library unlimited categories

Category class library unlimited classification

The following is the method of using this class library

include("Common/Category.class.php");
$Category = new Category("ArticleCategory",array('id','pid','name','fullname'));
$categoryList = $Category->getList();

1. Include the class library through include

2. Instantiate the class through new

3. Call the getList() method to obtain all classification lists

4. Return: all classification lists , you can display the reference by getting fullname.

The effect is as shown:

PHP Category class library unlimited categories

The following is the complete source code of the class library:

<?php
 
/**
 * 类功能:php无限分类
 * author:252588119@qq.com
 * 使用方法见:http://liqingbo.cn/blog-434.html
 */
class Category {
 
    private $model;                                                           //分类的数据表模型
    private $rawList = array();                                              //原始的分类数据
    private $formatList = array();                                           //格式化后的分类
    private $error = "";                                                      //错误信息
    private $icon = array(&#39;  │&#39;, &#39;  ├ &#39;, &#39;  └ &#39;);  //格式化的字符
    private $fields = array();                                               //字段映射,分类id,上级分类pid,分类名称name,格式化后分类名称fullname
 
    /**
     * 构造函数,对象初始化
     * @param array,object  $model      数组或对象,基于TP3.0的数据表模型名称,若不采用TP,可传递空值。
     * @param array         $field      字段映射,分类cid,上级分类pid,分类名称,格式化后分类名称fullname
     */
 
    public function __construct($model = &#39;&#39;, $fields = array()) {
        if (is_string($model) && (!empty($model))) {
            if (!$this->model = D($model))
                $this->error = $model . "模型不存在!";
        }
        if (is_object($model))
            $this->model = &$model;
 
        $this->fields[&#39;cid&#39;] = $fields[&#39;0&#39;] ? $fields[&#39;0&#39;] : &#39;id&#39;;
        $this->fields[&#39;pid&#39;] = $fields[&#39;1&#39;] ? $fields[&#39;1&#39;] : &#39;pid&#39;;
        $this->fields[&#39;name&#39;] = $fields[&#39;2&#39;] ? $fields[&#39;2&#39;] : &#39;name&#39;;
        $this->fields[&#39;fullname&#39;] = $fields[&#39;3&#39;] ? $fields[&#39;3&#39;] : &#39;fullname&#39;;
    }
 
    /**
     * 获取分类信息数据
     * @param array,string  $condition  查询条件
     * @param string        $orderby    排序
     */
    private function _findAllCat($condition, $orderby = NuLL) {
        $this->rawList = $this->model->where($condition)->order($orderby)->select();
    }
 
    /**
     * 返回给定上级分类$pid的所有同一级子分类
     * @param   int     $pid    传入要查询的pid
     * @return  array           返回结构信息
     */
    public function getChild($pid) {
        $childs = array();
        foreach ($this->rawList as $Category) {
            if ($Category[$this->fields[&#39;pid&#39;]] == $pid){
                $childs[] = $Category;
            }
        }
        return $childs;
    }
 
    /**
     * 递归格式化分类前的字符
     * @param   int     $cid    分类cid
     * @param   string  $space
     */
    private function _searchList($cid = 0, $space = "") {
        $childs = $this->getChild($cid);
        //下级分类的数组
        //如果没下级分类,结束递归
        if (!($n = count($childs))){
            return;
        }
        $m = 1;
        //循环所有的下级分类
        for ($i = 0; $i < $n; $i++) {
            $pre = "";
            $pad = "";
            if ($n == $m) {
                $pre = $this->icon[2];
            } else {
                $pre = $this->icon[1];
                $pad = $space ? $this->icon[0] : "";
            }
            $childs[$i][$this->fields[&#39;fullname&#39;]] = ($space ? $space . $pre : "") . $childs[$i][$this->fields[&#39;name&#39;]];
            $this->formatList[] = $childs[$i];
            $this->_searchList($childs[$i][$this->fields[&#39;cid&#39;]], $space . $pad . "  "); //递归下一级分类
            $m++;
        }
    }
 
    /**
     * 不采用数据模型时,可以从外部传递数据,得到递归格式化分类
     * @param   array,string     $condition    条件
     * @param   int              $cid          起始分类
     * @param   string           $orderby      排序
     * @return  array           返回结构信息
     */
    public function getList($condition = NuLL, $cid = 0, $orderby = NuLL) {
        unset($this->rawList, $this->formatList);
        $this->_findAllCat($condition, $orderby);
        $this->_searchList($cid);
        return $this->formatList;
    }
 
    /**
     * 获取结构
     * @param   array            $data         二维数组数据
     * @param   int              $cid          起始分类
     * @return  array           递归格式化分类数组
     */
    public function getTree($data, $cid = 0) {
        unset($this->rawList, $this->formatList);
        $this->rawList = $data;
        $this->_searchList($cid);
        return $this->formatList;
    }
 
    /**
     * 获取错误信息
     * @return  string           错误信息字符串
     */
    public function getError() {
        return $this->error;
    }
 
    /**
     * 检查分类参数$cid,是否为空
     * @param   int              $cid          起始分类
     * @return  boolean           递归格式化分类数组
     */
    private function _checkCatID($cid) {
        if (intval($cid)) {
            return true;
        } else {
            $this->error = "参数分类ID为空或者无效!";
            return false;
        }
    }
 
    /**
     * 检查分类参数$cid,是否为空
     * @param   int         $cid        分类cid
     */
    private function _searchPath($cid) {
        //检查参数
        if (!$this->_checkCatID($cid))
            return false;
        $rs = $this->model->find($cid);                                        //初始化对象,查找上级Id;
        $this->formatList[] = $rs;                                            //保存结果
        $this->_searchPath($rs[$this->fields[&#39;pid&#39;]]);
    }
 
    /**
     * 查询给定分类cid的路径
     * @param   int         $cid        分类cid
     * @return  array                   数组
     */
    public function getPath($cid) {
        unset($this->rawList, $this->formatList);
        $this->_searchPath($cid);                                               //查询分类路径
        return array_reverse($this->formatList);
    }
 
    /**
     * 添加分类
     * @param   array         $data        一维数组,要添加的数据,$data需要包含上级分类ID。
     * @return  boolean                    添加成功,返回相应的分类ID,添加失败,返回FALSE;
     */
    public function add($data) {
        if (empty($data))
            return false;
        return $this->model->data($data)->add();
    }
 
    /**
     * 修改分类
     * @param   array         $data     一维数组,$data需要包含要修改的分类cid。
     * @return  boolean                 组修改成功,返回相应的分类ID,修改失败,返回FALSE;
     */
    public function edit($data) {
        if (empty($data))
            return false;
        return $this->model->data($data)->save();
    }
 
    /**
     * 删除分类
     * @param   int         $cid        分类cid
     * @return  boolean                 删除成功,返回相应的分类ID,删除失败,返回FALSE
     */
    public function del($cid) {
        $cid = intval($cid);
        if (empty($cid))
            return false;
        $conditon[$this->fields[&#39;cid&#39;]] = $cid;
        return $this->model->where($conditon)->delete();
    }
 
    /**
     * 删除分类
     * @param   int         $cid        分类cid
     * @return  boolean                 删除成功,返回相应的分类ID及所有子ID 数组,返回FALSE
     */
    public function getIdArr($cid){
         $cid = !empty($cid) ? intval($cid) : 0;
         if (empty($cid)) return false;
         $list = $this->getList($condition = NuLL,$cid, $orderby = NuLL);
         foreach($list as $val){
             $idArr[] = $val[$this->fields[&#39;cid&#39;]];
         }
         unset($list);
         $idArr[] = $cid;
         return $idArr;
    }
 
}
?>

The demo contains a file folder, three files. The Helper folder contains unlimited classification processing classes. The folder is placed in the Application/Common/ directory. CategoryController.class.php is the controller file. It is used to demonstrate how to use unlimited classification processing classes. When using unlimited classifications in the controller, remember to introduce use first. Common\Helper\Category;category_add.html is a view file used to demonstrate how to call unlimited categories in the template.

go_category.sql is a classification table database file, for reference only. The core fields of the classification table are id: column id, title: column name, parent_id: parent column id, is_show: whether to display in the foreground, sort: frontend sorting.

The above is the detailed content of PHP Category class library unlimited categories. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!