Backend Development
PHP Tutorial
Implementing infinite generation family tree traversal and counting in PHP: Detailed explanation of recursive method
Implementing infinite generation family tree traversal and counting in PHP: Detailed explanation of recursive method

This article aims to solve the problem of infinite generation traversal and counting of family trees (or other hierarchical structures) in PHP. By analyzing the limitations of fixed-depth loops, the article details how to use recursive ideas to build a function that can handle any depth hierarchical structure. The content covers the core principles of recursive functions, the basic situation and the construction of recursive steps, PHP code implementation and key point analysis, and provides performance considerations and precautions to help developers achieve efficient and flexible hierarchical data processing.
Understanding the Problem: Limitations of Fixed-Depth Traversal
When working with hierarchical data, such as family trees, organizational structures, or file systems, a common requirement is to count the total number of descendant nodes under a node. If the level depth is fixed, we can achieve this through nested loops. For example, the original code snippet shows how to count the total number of family members within five generations:
function familyTree($id)
{
$total = 0;
foreach(family($id) as $child){
$total;
foreach(family($child->id) as $grand_child){
$total;
foreach(family($grand_child->id) as $great_grand_child){
$total;
foreach(family($great_grand_child->id) as $great_great_grand_child){
$total;
}
}
}
}
return $total;
}
Although this method is effective at certain depths, it has obvious limitations:
- Lack of flexibility : If the depth of the family tree increases or decreases, the code needs to be modified manually to add or delete nested loops.
- Difficult to scale : unable to handle "infinite generations" or hierarchies of arbitrary depth. Each additional generation requires an extra layer of loops, making the code verbose and difficult to maintain.
To overcome these limitations, we need a more general and elegant solution, and recursion is a powerful tool for this type of problem.
Introducing the solution: the power of recursion
Recursion is a technique where a function calls itself. When dealing with tree or hierarchical structures, recursion can naturally simulate self-similar structures, decomposing a large problem into smaller sub-problems that are similar to the original problem but smaller in size. For traversing and counting infinite generations of family trees, the advantages of recursion are:
- Simplicity : The code structure is clear and can handle any depth of hierarchy with a small amount of code.
- Universality : There is no need to preset a maximum depth, the recursion will continue deeper as long as there are child nodes.
- It makes sense : the family tree itself is a recursive structure (each member has its own descendant tree).
Building recursive functions: core principles
An effective recursive function usually contains two key parts:
- Base Case : This is the condition under which recursion stops. When the basic conditions are met, the function will directly return a value without making a recursive call. In the family tree example, the basic situation is to find a member (i.e., a leaf node) that has no children.
- Recursive Step : This is the part of the function call itself. In this step, the function processes the current node and makes recursive calls to each child node to combine the results of the subproblems.
Recursive logic for family tree counting
For family tree counting, our goal is to count the total number of members and all their descendants (including children, grandchildren, great-grandchildren, etc.).
- Basic situation : If a member has no children, then he himself is the end of the "family tree". At this time, he himself counts as 1 person.
- Recursive step : If a member has children, he is first counted as 1 person. He then needs to iterate through all the children and call the same function recursively on each child, adding up the total number of children and their descendants. The final total is the sum of the current members themselves plus all their children and their descendants.
PHP implementation example
In order to implement the above recursive logic, we first need an auxiliary function family($id), which can return the ID list of all its children based on the given member ID.
Assume the behavior of the family($id) function:
- If the member with ID $id has no children, family($id) returns null or an empty array[].
- If the member with ID $id has children, family($id) returns an array containing the IDs of all its children.
<?php // Hypothetical family function: Returns an array of child IDs based on ID, or an empty array or null if there are no children.
// In actual application, this function will obtain data from the database or other data sources function family($id) {
//Sample data (in actual projects, it will be queried from the database)
$data = [
1 => [2, 3], // 1 has children 2 and 3
2 => [4, 5], // 2 has children 4 and 5
3 => [], // 3 has no children 4 => [6], // 4 has children 6
5 => [], // 5 has no children 6 => [], // 6 has no children 7 => [8], // 7 has children 8
8 => [], // 8 has no children 9 => null // 9 has no children, return null as an example];
return $data[$id] ?? null; // If the ID does not exist, return null
}
/**
* Recursively calculate the total number of specified members and all their descendants*
* @param int $id member ID
* @return int The total number of members and all their descendants */
function familyTreeRecursive($id) {
$total = 0;
$children = family($id); // Get all children of the current member // Basic situation: If the current member has no children (family($id) returns null or an empty array)
// Then he himself is the leaf node, and only himself is counted.
// Note: If $children is an empty array, the foreach loop will not be executed and $total will still be 0.
// Subsequent $total will make it 1, so this explicit check can be simplified.
// But in order to clearly express the "basic situation", it is retained here.
if (is_null($children) || empty($children)) {
return 1; // The current member is a leaf node, only itself is counted}
// Recursive steps: Traverse all children and recursively call this function foreach ($children as $childId) {
$total = familyTreeRecursive($childId); // Accumulate the total number of each child and its descendants}
$total; // Add the current member to the total return $total;
}
// Example call echo "Total number of members 1 and their descendants: " . familyTreeRecursive(1) . " people\n"; // Expected: 1 (self) 2 3 (children) 4 5 6 (grandchildren) = 7
echo "Total number of members 2 and their descendants: " . familyTreeRecursive(2) . " people\n"; // Expected: 1 (self) 4 5 6 (grandchildren) = 4
echo "Total number of members 3 and their descendants: " . familyTreeRecursive(3) . " people\n"; // Expected: 1 (self)
echo "Total number of members 7 and their descendants: " . familyTreeRecursive(7) . " people\n"; // Expected: 1 (self) 8 (child) = 2
echo "Total number of members 9 and their descendants: " . familyTreeRecursive(9) . " people\n"; // Expected: 1 (self)
echo "Member 10 (does not exist) and total number of descendants: " . familyTreeRecursive(10) . " people\n"; // Expected: 1 (self)
?>
Code analysis:
- family($id) function : This is a mock function used to get the list of children with a specified ID. In a real application, this would be a database query or other data access logic. It returns an array of children's IDs, or null or an empty array if there are no children.
- familyTreeRecursive($id) function :
- $total = 0;: Initialize the counter.
- $children = family($id);: Get the list of children of the current member.
- if (is_null($children) || empty($children)): This is the base case . If family($id) returns null or an empty array, it means that the current member has no children. At this time, the member is a leaf node and only counts itself, so it returns 1; directly.
- foreach ($children as $childId): This is the recursive step . If the current member has children, these children are traversed.
- $total = familyTreeRecursive($childId);: For each child, call the familyTreeRecursive function recursively to obtain the total number of the child and all its descendants, and add them to $total.
- $total ;: After all children and their descendants have been counted, include the current member himself in the total.
- return $total;: Returns the final total number of people.
Notes and optimization
- Accurate judgment of the basic situation : Ensure the logical rigor of the basic situation, which is the key to recursive termination. If the basic situation is judged incorrectly or missing, infinite recursion (stack overflow) may result. In the example, we handle the two "childless" cases of null and empty array.
- Performance considerations :
- Stack Overflow : For very deep hierarchies (e.g., thousands of levels deep), PHP's default recursion depth limit may cause stack overflow errors. In this case, you may want to consider using an iterative approach (e.g., stack- or queue-based breadth-first/depth-first traversal) instead of recursion.
- Repeated queries : If the family($id) function performs database queries in each recursive call, it may cause a large number of database connections and query operations, affecting performance. You can consider using a caching mechanism (such as Redis, Memcached) or loading all relevant data into memory at once (if the amount of data is controllable) to reduce repeated queries.
- Data structure : Make sure the data structure returned by the family($id) function is consistent and easy to process. In the example, we assume it returns an array of child IDs. If an array of objects is returned, you need to adjust the access method inside the foreach loop (for example, familyTreeRecursive($child->id)).
- Error handling : In actual applications, the family($id) function may fail because the ID does not exist or other reasons. Appropriate error handling should be added, such as checking that $id is valid or that the return value of family($id) is as expected.
Summarize
Through recursion, we can elegantly and efficiently solve the traversal and counting problems of infinite generation hierarchies (such as family trees). Its core lies in clearly defined base cases (recursion termination conditions) and recursive steps (decomposing the problem into smaller subproblems and calling themselves). Although recursion may run the risk of stack overflow when dealing with very deep levels, in most common scenarios it is the preferred method for working with tree-shaped data. Understanding and skillfully using recursion is one of the essential skills for every professional PHP developer.
The above is the detailed content of Implementing infinite generation family tree traversal and counting in PHP: Detailed explanation of recursive method. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20521
7
13633
4
Instantiation mechanism and reflection application of PHP attributes
Mar 13, 2026 pm 12:27 PM
PHP properties do not automatically instantiate their class constructors when declared. They are essentially metadata attached to code elements and need to be explicitly read and instantiated through PHP's reflection API in order to trigger the execution of their constructors. Understanding this mechanism is critical to correctly utilizing properties to implement advanced functionality such as framework routing, validation, or ORM mapping.
PHP gRPC client JWT authentication practice guide
Mar 14, 2026 pm 01:00 PM
This article details how to correctly configure JWT (JSON Web Token) for authentication in the PHP gRPC client. The core is to set the request metadata in the standard Authorization: Bearer format through the update_metadata callback function to ensure that the server can correctly parse and verify the client's identity, thereby avoiding common authentication errors.
How to display hospital/center name instead of ID in patient query results
Mar 13, 2026 pm 12:45 PM
This article explains in detail how to use SQL table connections to replace the originally displayed hospital ID (h_id) with the corresponding hospital or center name when querying patient data to improve data readability and user experience.
How to batch extract the values of all keys with the same name (such as 'id') in a JSON object in PHP
Mar 14, 2026 pm 12:42 PM
This article explains in detail how to use json_decode() and array_column() to efficiently extract all values of specified keys (such as id) in nested JSON data at all levels, avoiding manual traversal and taking into account performance and readability.
PHP runtime getting and monitoring script maximum memory limit (bytes)
Apr 01, 2026 am 06:42 AM
This article aims to guide PHP developers on how to accurately obtain the maximum memory limit (in bytes) of a script at runtime, and combine it with real-time memory usage for effective monitoring. By parsing the memory_limit configuration string and using built-in functions, an early warning mechanism for memory consumption is implemented to avoid fatal errors caused by memory overflow.
How to append corresponding value to the end of each subarray of PHP array
Mar 14, 2026 pm 12:51 PM
This article describes how to append the values of a one-dimensional index array to the end of each sub-array of another two-dimensional array in order, solving alignment problems caused by index offsets (such as $array2 starting from key 1), and providing a safe and readable implementation solution.
Tutorial on flattening nested arrays into a single array in PHP
Mar 13, 2026 am 02:57 AM
This tutorial details how to flatten a nested array structure containing multiple sub-arrays into a single array in PHP. This can be achieved efficiently and concisely by utilizing PHP's array_merge function combined with the array unpacking operator (...) to extract all internal elements into a top-level array, suitable for processing collections or grouped data.
The reason why explode() returns nested arrays in PHP and its correct usage
Mar 14, 2026 pm 12:39 PM
explode() itself returns a one-dimensional array, but due to misuse of the array append syntax $myarray[] = ..., the result is wrapped into additional levels, forming an "array of arrays"; the correction method is to assign values directly instead of appending.





