Building a Tree Structure from an Array List
Given an array list of items with hierarchical relationships, how can we efficiently transform it into a nested tree structure?
Solution:
To achieve this conversion without using complex database optimizations, we can employ a recursive function:
$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 arranges the items into a nested hierarchical structure, representing the parent-child relationships among them. The resulting tree structure can be printed using print_r.
By leveraging a recursive function, we can efficiently transform an array list into a tree structure, allowing for easy navigation and organization of data.
The above is the detailed content of How to Efficiently Build a Tree Structure from a Hierarchical Array List?. For more information, please follow other related articles on the PHP Chinese website!