Home >Backend Development >PHP Tutorial >How to Recursively Build a Multidimensional Array from Flat Database Results?
Building a Multidimensional Array from Database Results Recursively
To retrieve hierarchical data structures, such as page and category menus, from a flat database result, a recursive function can be employed. This function will take the original array and organize it into nested arrays based on parent-child relationships.
The Function:
function buildTree(array $elements, $parentId = 0) { $branch = array(); foreach ($elements as $element) { if ($element['parent_id'] == $parentId) { $children = buildTree($elements, $element['id']); if ($children) { $element['children'] = $children; } $branch[] = $element; } } return $branch; }
How it Works:
Example Usage:
To convert the example database result into a multidimensional array using this function:
$tree = buildTree($rows);
Where $rows is the original array of database results.
Output:
The resulting hierarchical array will resemble the desired output:
Array ( [0] => Array ( [id] => 1 [parent_id] => 0 [title] => Parent Page [children] => Array ( [0] => Array ( [id] => 2 [parent_id] => 1 [title] => Sub Page [children] => Array ( [0] => Array ( [id] => 3 [parent_id] => 1 [title] => Sub Sub Page ) ) ) ) [children] => Array ( [0] => Array ( [id] => 4 [parent_id] => 0 [title] => Another Parent Page [children] => Array ( ) ) ) ) )
The above is the detailed content of How to Recursively Build a Multidimensional Array from Flat Database Results?. For more information, please follow other related articles on the PHP Chinese website!