search
HomeBackend DevelopmentPHP TutorialPHP infinite classification best practices

Infinite Classification

  • is a very common and necessary function, almost every project has it.

  • Application scenarios: drop-down lists, tree lists, etc.

Types of infinite classification

  • Front-end implementation (The front-end framework has generally been implemented, and it can be generated as long as the back-end transmits data to the front-end in the specified format)

  • Back-end Implementation(The following mainly talks about this kind of implementation)

Infinitely multiple implementations

  • The first type (recommended)

function infiniteSort($data, $showFName, $titleFName, $pidFName = 'pid', $idFName = 'id', $levelFName = 'level', $pid = 0, $level = 0)
{
    $tree = array();

    foreach ($data as $key => $value) {

        if ($value[$pidFName] == $pid) {
            $value[$levelFName] = $level;
            $value[$showFName] = str_repeat('  ', $level) . '|-' . $value[$titleFName];
            $tree[] = $value;
            unset($data[$key]);
            $tempArr = infiniteSort($data, $showFName, $titleFName, $pidFName, $idFName, $level, $value[$idFName], $level + 1);
            if(!empty($tempArr)){
                $tree = array_merge($tree, $tempArr);
            }
        }

    }

    return $tree;
}

Note:
1, $data All data that has been sorted by asc
2, $showFName Display name Field name of the title (formatted)
3. $titleFName Field name of the title (unformatted)
4. $levelFName Level field name
5, $pidFName The field name of the parent id
6, $idFName The field name of the id

  • The second type (using reference variables)

/**
 * 无限级分类
 * @param Array $treeList //接受处理完成数据的数组
 * @param Array $data //数据库里获取的结果集
 * @param String $level //格式化层级字段名
 * @param Int $pid
 * @param Int $count //第几级分类
 */
function tree(&$treeList, &$data, $level, $show_name, $field_name, $field_pid = 'pid', $field_id = 'id', $pid = 0, $count = 0)
{
    foreach ($data as $key => $value) {

        if ($value[$field_pid] == $pid) {
            $value[$level] = $count;
            $value[$show_name] = str_repeat('    ',$count).'|-'.$value[$field_name];
            $treeList[] = $value;
            unset($data[$key]);
            tree($treeList, $data, $level, $show_name, $field_name,$field_pid, $field_id, $value[$field_id], $count+1);
        }

    }
}

Note:
1, $data All data that has been sorted by asc
2 , the returned infinite list data is stored in $treeList

  • The third type (there are restrictions on using static variables: if a request is called twice to achieve 2 Infinite level classification will cause problems, so it is not recommended)

    public function getTree($list, $parent_id, $level=0) {
        //应该是静态的局部变量,这样才能保证,在递归调用时,所有
        //的getTree方法,操作的是一个Tree空间。
        static $tree = array();//保存找到的分类的数组
        //遍历所有分类,通过parent_id判断,哪些是我们正在查找的
        foreach($list as $row) {
            //判断当前所遍历的分类$row, 是否是当前需要查找的子分类
            if($row['pid'] == $parent_id) {
                //找到了一个分类
                //存起来,存哪?
                $row['level'] = $level;
                $tree[] = $row;
                //继续查找当前$row所代表的分类的子分类
                $this->getTree($list, $row['id'], $level+1);
            }
        }
        return $tree;
    }

Note:
1, $list All data that has been sorted by asc

Unlimited classification

  • is a very common and necessary function, almost every project has it.

  • Application scenarios: drop-down lists, tree lists, etc.

Types of infinite classification

  • Front-end implementation (The front-end framework has generally been implemented, and it can be generated as long as the back-end transmits data to the front-end in the specified format)

  • Back-end Implementation(The following mainly talks about this kind of implementation)

Infinitely multiple implementations

  • The first type (recommended)

function infiniteSort($data, $showFName, $titleFName, $pidFName = 'pid', $idFName = 'id', $levelFName = 'level', $pid = 0, $level = 0)
{
    $tree = array();

    foreach ($data as $key => $value) {

        if ($value[$pidFName] == $pid) {
            $value[$levelFName] = $level;
            $value[$showFName] = str_repeat('  ', $level) . '|-' . $value[$titleFName];
            $tree[] = $value;
            unset($data[$key]);
            $tempArr = infiniteSort($data, $showFName, $titleFName, $pidFName, $idFName, $level, $value[$idFName], $level + 1);
            if(!empty($tempArr)){
                $tree = array_merge($tree, $tempArr);
            }
        }

    }

    return $tree;
}

Note:
1, $data All data that has been sorted by asc
2,$ showFName Display the field name of the name (formatted)
3, $titleFName The field name of the title (unformatted)
4, $levelFName Hierarchical field name
5, $pidFName Field name of parent id
6, $idFName Field name of id

  • Second type (using reference variables)

/**
 * 无限级分类
 * @param Array $treeList //接受处理完成数据的数组
 * @param Array $data //数据库里获取的结果集
 * @param String $level //格式化层级字段名
 * @param Int $pid
 * @param Int $count //第几级分类
 */
function tree(&$treeList, &$data, $level, $show_name, $field_name, $field_pid = 'pid', $field_id = 'id', $pid = 0, $count = 0)
{
    foreach ($data as $key => $value) {

        if ($value[$field_pid] == $pid) {
            $value[$level] = $count;
            $value[$show_name] = str_repeat('    ',$count).'|-'.$value[$field_name];
            $treeList[] = $value;
            unset($data[$key]);
            tree($treeList, $data, $level, $show_name, $field_name,$field_pid, $field_id, $value[$field_id], $count+1);
        }

    }
}

Note:
1, $data All data that has been sorted by asc
2. The returned infinite-level list data is stored in $treeList

  • The third type (there are restrictions on using static variables: if one request calls Implementing two infinite levels of classification twice will cause problems, so it is not recommended)

    public function getTree($list, $parent_id, $level=0) {
        //应该是静态的局部变量,这样才能保证,在递归调用时,所有
        //的getTree方法,操作的是一个Tree空间。
        static $tree = array();//保存找到的分类的数组
        //遍历所有分类,通过parent_id判断,哪些是我们正在查找的
        foreach($list as $row) {
            //判断当前所遍历的分类$row, 是否是当前需要查找的子分类
            if($row['pid'] == $parent_id) {
                //找到了一个分类
                //存起来,存哪?
                $row['level'] = $level;
                $tree[] = $row;
                //继续查找当前$row所代表的分类的子分类
                $this->getTree($list, $row['id'], $level+1);
            }
        }
        return $tree;
    }

Note:
1, $list All data that has been sorted by asc

For more articles related to PHP infinite classification best practices, please pay attention to 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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft