Created
March 15, 2017 16:37
-
-
Save fmtarif/a49ec37910f51f5940ae2c2a3108a3f2 to your computer and use it in GitHub Desktop.
#php Recursive function that creates a parent children nested array of unlimited hierarchy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * @param $elements format like following | |
| * [ | |
| 'id' => 1, | |
| 'name' => 'root1', | |
| 'parent_id' => 0 | |
| ] | |
| */ | |
| 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment