Recursively Generating Multidimensional Arrays from a Database Result
In this scenario, the goal is to construct a nested array representation of hierarchical data retrieved from a database query. The result table contains pages or categories with parent-child relationships.
To accomplish this, we employ a recursive function, buildTree(). This function takes an array of elements and an optional parent ID (defaulting to 0). It iterates through each element, identifying those that have the specified parent ID.
For each child element, the function calls itself recursively to obtain its subtree. The child element is then augmented with its children, resulting in a hierarchical structure. This process continues until all elements are processed, yielding a nested array that mirrors the hierarchical data structure.
Example
Consider the database table provided earlier:
id | parent_id | title |
---|---|---|
1 | 0 | Parent Page |
2 | 1 | Sub Page |
3 | 2 | Sub Sub Page |
4 | 0 | Another Parent Page |
Using the buildTree() function, we can generate the desired nested array:
$elements = [ ['id' => 1, 'parent_id' => 0, 'title' => 'Parent Page'], ['id' => 2, 'parent_id' => 1, 'title' => 'Sub Page'], ['id' => 3, 'parent_id' => 2, 'title' => 'Sub Sub Page'], ['id' => 4, 'parent_id' => 0, 'title' => 'Another Parent Page'], ]; $tree = buildTree($elements);
The output $tree will be:
[ [ 'id' => 1, 'parent_id' => 0, 'title' => 'Parent Page', 'children' => [ [ 'id' => 2, 'parent_id' => 1, 'title' => 'Sub Page', 'children' => [ [ 'id' => 3, 'parent_id' => 2, 'title' => 'Sub Sub Page', ] ] ] ] ], [ 'id' => 4, 'parent_id' => 0, 'title' => 'Another Parent Page', ] ]
This nested array preserves the hierarchical relationships defined in the database table, enabling efficient access and processing of the data in nested structures.
The above is the detailed content of How to Recursively Build a Multidimensional Array from Hierarchical Database Data?. For more information, please follow other related articles on the PHP Chinese website!