In this article, we will discuss how to generate "Parent Child Tree PHP Recursion".
Using the recursive function and joining in MYSQL are the common ways to create tree structures. Both methods have exponent time complexity 2^O(n). So, the computational time is very high. For every element that the user adds to the dataset, the computational time complexity will be double.
The best practice while building the tree structure is to use references. Using this method trees can be built with only one password. This gives linear time complexity which can be represented in mathematical notation like O(n). The user will get only a small and constant increase in computational time for every element that is added to the dataset.
Treeview in PHP can be used to construct hierarchical lists such as menus with sub-menus, category trees, taxonomy trees, and site maps.
Code to generate tree by using the recursive function:
The following code is a modified version of the Tommay Lacrios version.
function buildTree(array $dataset)
{
$tree = array();
//Most datasets are enumerative arrays but we required an associative array because the same ID used for addressing parents.
$references = array();
foreach ($dataset as $id => &$node) {
// Add the node to an associative array using the ID as a key-value
$references[$node['id']] = &$node;
// Add an empty placeholder for children of the parent node
$node['children'] = array();
// Root node can be added directly to the tree because we have no value for comparison
if (is_null($node['parentId'])) {
$tree[$node['id']] = &$node;
} else {
// We need to set a reference of a parent node, for the modes who are not root
$references[$node['parentId']]['children'][$node['id']] = &$node;
}
}
return $tree;
}
Conclusion
In this article, we discussed the Recursive function to generate a parent/child tree. The code we discussed is considerably easier and more effective. Hope it helped.