Home >Backend Development >PHP Tutorial >How to Efficiently Build a Tree Structure from a Hierarchical Array List?

How to Efficiently Build a Tree Structure from a Hierarchical Array List?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 11:01:10709browse

How to Efficiently Build a Tree Structure from a Hierarchical Array List?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn