search
HomeBackend DevelopmentPHP TutorialCode examples for PHP Infinitus classification (recursive and tree)

This article brings you code examples (recursion and trees) of PHP Infinitus classification. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

(1) .Recursive implementation

function getTree($array, $pid =0, $level = 0){
//声明静态数组,避免递归调用时,多次声明导致数组覆盖 
static $list = []; 
foreach ($array as $key => $value){     
//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点  
if ($value['pid'] == $pid){
//父节点为根节点的节点,级别为0,也就是第一级
$value['level'] = $level;
//把数组放到list中
$list[] = $value;
//把这个节点从数组中移除,减少后续递归消耗           
unset($array[$key]);           
//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1          
getTree($array, $value['id'], $level+1);
        }
    } 
return $list;
}

The result is as shown in the figure:

(2) .Tree structure

function getTree($items,$pid ="pid") {
    $map  = [];
    $tree = []; 
foreach ($items as &$it){ $map[$it['id']] = &$it; }  
//数据的ID名生成新的引用索引树   
foreach ($items as &$at){
        $parent = &$map[$at[$pid]];    
if($parent) {
            $parent['children'][] = &$at;
        }else{
            $tree[] = &$at;
        }
    }
return $tree;
}

The result is as shown:

The above is the detailed content of Code examples for PHP Infinitus classification (recursive and tree). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Understanding Stack vs. Queue Operations with PHP Array FunctionsUnderstanding Stack vs. Queue Operations with PHP Array FunctionsAug 08, 2025 am 10:50 AM

PHParrayscansimulatestackandqueuebehaviorsusingspecificfunctions,withkeydifferencesinlogicandperformance.Forastack(LIFO),1.usearray_push()toaddelementstotheend,2.usearray_pop()toremovefromtheend—fastandefficient.Foraqueue(FIFO),1.usearray_push()toadd

.htaccess URL rewrite: Common errors and best practices for achieving beautiful URLs.htaccess URL rewrite: Common errors and best practices for achieving beautiful URLsAug 08, 2025 am 10:09 AM

This article explains in detail how to rewrite dynamic URLs (such as domain/some.php?f=query-string) into more aesthetically pleasing static forms (such as domain/query-string) using the .htaccess and mod_rewrite modules. The focus is on analyzing common "slash" errors in the RewriteRule pattern and providing the correct configuration method to help developers effectively implement URL optimization.

Navigating Key Gaps and Re-indexing Strategies in PHP ArraysNavigating Key Gaps and Re-indexing Strategies in PHP ArraysAug 08, 2025 am 08:04 AM

After deleting elements with unset(), the PHP index array will have key gaps, resulting in keys no longer continuous; 2. The key gap will affect loops, JSON encoding and functions that rely on continuous indexes; 3. The array can be re-indexed through array_values() to generate continuous keys starting from 0; 4. The array_filter() will retain the original key, and the array_values() needs to be called manually to re-index; 5. Use array_splice() to delete elements to automatically re-index; 6. Before JSON encoding, you should ensure that the keys are continuous, otherwise objects may be output instead of arrays; 7. When the keys of the associative array are meaningful, re-index should be avoided to avoid losing key names; 8. Only when the array needs to be used as an ordered list

Elegant Array Merging in Modern PHP with the Spread Operator (...)Elegant Array Merging in Modern PHP with the Spread Operator (...)Aug 08, 2025 am 07:10 AM

PHP8.1enhancesarraymergingwiththespreadoperator(...),whichunpacksiterablesintoarrayliterals,offeringcleanersyntaxthanarray_merge().1.Itworksinarraydeclarations,mergingindexedarraysintuitively:[...$a,...$b]preservesorder.2.Forassociativearrays,laterva

Unlocking Array Power: Initialization Techniques for Data ManipulationUnlocking Array Power: Initialization Techniques for Data ManipulationAug 08, 2025 am 05:59 AM

Literalinitializationisbestforsmall,staticdatasetsusingsyntaxlikeconstarr=[1,2,3].2.ConstructoranddynamicmethodslikenewArray(n)orArray(n).fill()areidealforpredefinedsizesorrepeatedvalues,withcautionagainstsparsearraysinJavaScript.3.Convertingexisting

Implementing Stacks and Queues Using PHP's Native Array FunctionsImplementing Stacks and Queues Using PHP's Native Array FunctionsAug 08, 2025 am 02:58 AM

PHP arrays can implement stacks and queues through built-in functions. 1. The stack uses array_push() and array_pop(), and the time complexity is O(1), which is suitable for efficient operations; 2. The queue uses array_push() and array_shift(), but array_shift() is O(n), and the performance decreases with the amount of data; 3. The production environment should give priority to using SplStack and SplQueue, which is based on a bidirectional linked list, and the operations are O(1), which has better performance; 4. Native arrays are suitable for small-scale data or prototype development, and should be avoided in queues during large-scale high-frequency operations.

The Power of `?`: Effectively Utilizing Nullable Types in PHPThe Power of `?`: Effectively Utilizing Nullable Types in PHPAug 08, 2025 am 01:50 AM

?In PHP, the type can be empty, which can improve the type safety and readability of the code; 1. When used for optional parameters, make sure that the incoming value is the specified type or null; 2. For return values that may not be found, clearly inform the caller that it may return null; 3. For scenarios where optional data exists such as APIs, accurately model the data structure; when used, it should only be used when null makes sense, avoid repeated definitions with the default null, combine the null and handle null values with the ?? and ?-> operators, and note that it cannot be used for void types. After PHP8, string is equivalent to string|null, but the former is more concise, and reasonable use can significantly reduce runtime errors.

Simulating Post-Test Loops in Algorithms with PHP's do-whileSimulating Post-Test Loops in Algorithms with PHP's do-whileAug 08, 2025 am 01:22 AM

Thedo-whileloopinPHPisidealforpost-testlogicbecauseitguaranteesatleastoneexecutionoftheloopbodybeforeevaluatingthecondition.1.Useitwhenanactionmustrunatleastoncebeforecheckingrepetition,suchasuserinputvalidation,wherethepromptmustappearbeforevalidati

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft