How to Efficiently Convert an Array of Records into a Tree Structure
In this scenario, you have an array of records representing a hierarchical structure. Each record has an ID, a parent ID, and a name. The objective is to transform this array into a nested tree structure, where the root node has children nodes, which in turn may have their own children nodes.
To achieve this, a recursive function named createTree is employed. This function takes two parameters: a reference to the array of records and a parent array. It iterates through the parent array and for each parent, it checks if there are any child records in the array of records. If child records exist, it calls the createTree function recursively to process them, and assigns the result to the children property of the parent.
Following is an example:
$arr = array( array('id' => 100, 'parentid' => 0, 'name' => 'a'), array('id' => 101, 'parentid' => 100, 'name' => 'a'), array('id' => 102, 'parentid' => 101, 'name' => 'a'), array('id' => 103, 'parentid' => 101, 'name' => 'a'), ); $new = array(); foreach ($arr as $a){ $new[$a['parentid']][] = $a; } $tree = createTree($new, array($arr[0])); print_r($tree); function createTree(&$list, $parent){ $tree = array(); foreach ($parent as $k =>$l){ if(isset($list[$l['id']])){ $l['children'] = createTree($list, $list[$l['id']]); } $tree[] = $l; } return $tree; }
This code will output the desired tree structure. The createTree function recursively converts the parent records to children, creating a hierarchical tree representation of the data. Note that the function operates on a reference to the input array, allowing changes to be propagated back to the original array.
The above is the detailed content of How to Efficiently Convert an Array of Records into a Nested Tree Structure?. For more information, please follow other related articles on the PHP Chinese website!