Home > Backend Development > PHP Tutorial > How to Efficiently Convert an Array of Records into a Nested Tree Structure?

How to Efficiently Convert an Array of Records into a Nested Tree Structure?

Barbara Streisand
Release: 2024-11-29 12:55:11
Original
657 people have browsed it

How to Efficiently Convert an Array of Records into a Nested Tree Structure?

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;
}
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template