Convert a Flat Array into a Nested Array Using Recursion

Problem: How to Convert a Flat Array into a Nested Array Using Recursion in PHP?

I have a flat array with items that have parent-child relationships. Each item has an ID and a parent_id. I want to convert this flat array into a nested array where each parent contains its children recursively. How can I achieve this in PHP?

Here is an example of the flat array:

$items = [
['id' => 1, 'parent_id' => 0, 'name' => 'Parent 1'],
['id' => 2, 'parent_id' => 1, 'name' => 'Child 1.1'],
['id' => 3, 'parent_id' => 1, 'name' => 'Child 1.2'],
['id' => 4, 'parent_id' => 2, 'name' => 'Child 1.1.1'],
['id' => 5, 'parent_id' => 0, 'name' => 'Parent 2'],
['id' => 6, 'parent_id' => 5, 'name' => 'Child 2.1']
];

I want to transform it into a nested structure like this:

[
[
'id' => 1,
'parent_id' => 0,
'name' => 'Parent 1',
'children' => [
[
'id' => 2,
'parent_id' => 1,
'name' => 'Child 1.1',
'children' => [
[
'id' => 4,
'parent_id' => 2,
'name' => 'Child 1.1.1'
]
]
],
[
'id' => 3,
'parent_id' => 1,
'name' => 'Child 1.2'
]
]
],
[
'id' => 5,
'parent_id' => 0,
'name' => 'Parent 2',
'children' => [
[
'id' => 6,
'parent_id' => 5,
'name' => 'Child 2.1'
]
]
]
]

How can I do this using a recursive function in PHP?

 

Solution: Creating a Nested Array Using a Recursive Function in PHP

To achieve this, you need a recursive function that builds the tree structure by looking for children of each item. The function will group items by their parent_id and attach them to their corresponding parents.

To convert the PHP nested array to HTML unordered list

  • format than you can find the solution here   Click Here  to check.

    Step-by-Step Implementation:

    1. First, we create a function that takes the flat array and the parent_id to find children recursively.
    2. We then loop through the array and attach child nodes to their respective parents.

    Here’s how to do it:

    function buildTree(array $items, $parentId = 0) {
    $branch = [];

    foreach ($items as $item) {
    if ($item['parent_id'] == $parentId) {
    $children = buildTree($items, $item['id']);
    if ($children) {
    $item['children'] = $children;
    }
    $branch[] = $item;
    }
    }

    return $branch;
    }

    // Example flat array
    $items = [
    ['id' => 1, 'parent_id' => 0, 'name' => 'Parent 1'],
    ['id' => 2, 'parent_id' => 1, 'name' => 'Child 1.1'],
    ['id' => 3, 'parent_id' => 1, 'name' => 'Child 1.2'],
    ['id' => 4, 'parent_id' => 2, 'name' => 'Child 1.1.1'],
    ['id' => 5, 'parent_id' => 0, 'name' => 'Parent 2'],
    ['id' => 6, 'parent_id' => 5, 'name' => 'Child 2.1']
    ];

    // Convert flat array to nested array
    $nestedArray = buildTree($items);

    echo '<pre>';
    print_r($nestedArray);
    echo '</pre>';

    Explanation:

    • The buildTree() function takes two parameters: the flat array and the parentId it should start from (default is 0, representing the top-level items).
    • It loops through the items to check which ones have the matching parent_id.
    • For each item that matches, it recursively calls buildTree() to check if that item has children. If it does, it adds them under a children key.
    • The function returns the built tree for the given parent_id.

    Output:

    The resulting nested array will be:

    Array
    (
    [0] => Array
    (
    [id] => 1
    [parent_id] => 0
    [name] => Parent 1
    [children] => Array
    (
    [0] => Array
    (
    [id] => 2
    [parent_id] => 1
    [name] => Child 1.1
    [children] => Array
    (
    [0] => Array
    (
    [id] => 4
    [parent_id] => 2
    [name] => Child 1.1.1
    )

    )

    )

    [1] => Array
    (
    [id] => 3
    [parent_id] => 1
    [name] => Child 1.2
    )

    )

    )

    [1] => Array
    (
    [id] => 5
    [parent_id] => 0
    [name] => Parent 2
    [children] => Array
    (
    [0] => Array
    (
    [id] => 6
    [parent_id] => 5
    [name] => Child 2.1
    )

    )

    )

    )

    Conclusion:

    Using a recursive function to build a tree structure from a flat array is a powerful technique in PHP. It’s particularly useful when dealing with hierarchical data like categories, menus, or organizational charts. By leveraging recursion, you can easily create a nested array where each parent contains its respective children.

Related Blog