In cases where data is stored in an adjacency list format, a recursive function can efficiently retrieve child and grandchild nodes for a specific parent node. This approach offers a tailored solution for identifying all nodes below a given parent.
Here's an implementation of a recursive function that accomplishes this task:
function fetch_recursive($tree, $parent_id, $parent_found = false, $list = array()) { foreach ($tree as $key => $node) { if ($parent_found || $key == $parent_id) { $row_data = array(); foreach ($node as $field => $value) { if ($field != 'children') { $row_data[$field] = $value; } } $list[] = $row_data; if (isset($node['children']) && !empty($node['children'])) { $list = array_merge($list, fetch_recursive($node['children'], $parent_id, true)); } } elseif (isset($node['children']) && !empty($node['children'])) { $list = array_merge($list, fetch_recursive($node['children'], $parent_id)); } } return $list; }
Assuming you have already built a tree structure from the data using a separate function, you can utilize this recursive function to retrieve all child and grandchild nodes for a specific parent node.
For instance, if you have a tree structured as follows:
Array ( [1] => Array ( [id] => 1 [name] => Electronics [parent_id] => 0 [children] => Array ( [2] => Array ( [id] => 2 [name] => Televisions [parent_id] => 1 [children] => Array ( [4] => Array ( [id] => 4 [name] => Tube [parent_id] => 2 [children] => Array() ) [5] => Array ( [id] => 5 [name] => LCD [parent_id] => 2 [children] => Array() ) [6] => Array ( [id] => 6 [name] => Plasma [parent_id] => 2 [children] => Array() ) ) ) [3] => Array ( [id] => 3 [name] => Portable Electronics [parent_id] => 1 [children] => Array ( [7] => Array ( [id] => 7 [name] => Mp3 Players [parent_id] => 3 [children] => Array ( [10] => Array ( [id] => 10 [name] => Flash [parent_id] => 7 [children] => Array() ) ) ) [8] => Array ( [id] => 8 [name] => CD Players [parent_id] => 3 [children] => Array() ) [9] => Array ( [id] => 9 [name] => 2 Way Radios [parent_id] => 3 [children] => Array() ) ) ) ) ) )
To retrieve all child nodes of, say, node with ID 3, you would call the function like this:
$parent_id = 3; $child_nodes = fetch_recursive($tree, $parent_id);
The $child_nodes variable will now contain an array with all child nodes of the node with ID 3, such as:
Array ( [0] => Array ( [id] => 3 [name] => Portable Electronics [parent_id] => 1 ) [1] => Array ( [id] => 7 [name] => Mp3 Players [parent_id] => 3 ) [2] => Array ( [id] => 10 [name] => Flash [parent_id] => 7 ) [3] => Array ( [id] => 8 [name] => CD Players [parent_id] => 3 ) [4] => Array ( [id] => 9 [name] => 2 Way Radios [parent_id] => 3 ) )
The above is the detailed content of How to retrieve all nested child nodes of a specific parent in a tree structure using a recursive PHP function?. For more information, please follow other related articles on the PHP Chinese website!