Backend Development 3 min read

Converting Arrays to Tree Structures and Back in PHP

This article demonstrates how to transform a flat array into a hierarchical tree structure and reverse the process in PHP, providing step‑by‑step code examples for building a tree using parent‑child relationships and converting the tree back into a flat list.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Converting Arrays to Tree Structures and Back in PHP

This article from the PHP Chinese community presents a tutorial on converting an array to a tree structure and back using PHP.

First, an example controller method public function index() creates a sample data array with id, parent_id, and name fields, then calls $this->list_to_tree($data) and dumps the result.

public function index()
{
    $data = [
        ['id'=>1, 'parent_id'=>0, 'name'=>'第一个'],
        ['id'=>2, 'parent_id'=>0, 'name'=>'第二个'],
        ['id'=>3, 'parent_id'=>1, 'name'=>'第三个'],
    ];
    $r = $this->list_to_tree($data);
    dump($r);
}

The list_to_tree function builds a hierarchical tree by first creating a reference map of items keyed by their primary key, then iterating over the list to attach each item to its parent based on parent_id . Items whose parent matches the root are added to the top‑level $tree array; otherwise they are placed under the children key of their parent.

function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $child = 'children')
{
    $tree = array();
    if (is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string)$root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

The tree_to_list function performs the inverse operation: it recursively traverses the tree, removes the children field from each node, and merges the flattened nodes into a single array.

function tree_to_list($tree = [], $children = 'children')
{
    if (empty($tree) || !is_array($tree)) {
        return $tree;
    }
    $arrRes = [];
    foreach ($tree as $k => $v) {
        $arrTmp = $v;
        unset($arrTmp[$children]);
        $arrRes[] = $arrTmp;
        if (!empty($v[$children])) {
            $arrTmp = tree_to_list($v[$children]);
            $arrRes = array_merge($arrRes, $arrTmp);
        }
    }
    return $arrRes;
}

By using these two functions, developers can easily switch between flat and hierarchical representations of data, which is useful for rendering nested menus, category trees, or organizational charts.

Backend DevelopmentphpData StructureRecursive FunctionArray to Tree
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.