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:
I want to transform it into a nested structure like this:
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 <ul> <li> format than you can find the solution here Click Here to check.
Step-by-Step Implementation:
- First, we create a function that takes the flat array and the
parent_id
to find children recursively. - We then loop through the array and attach child nodes to their respective parents.
Here’s how to do it:
Explanation:
- The
buildTree()
function takes two parameters: the flat array and theparentId
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 achildren
key. - The function returns the built tree for the given
parent_id
.
Output:
The resulting nested array will be:
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.