Created
April 27, 2019 17:10
-
-
Save meysampg/c51fadb37fde78e74e56614f505e54d4 to your computer and use it in GitHub Desktop.
Create a tree from a flat array (like data retrieved from DB)
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 | |
| // Data from stackoverflow | |
| $a = array( | |
| array('id'=>100, 'parentid'=>0, 'name'=>'a0'), | |
| array('id'=>102, 'parentid'=>101, 'name'=>'a012'), | |
| array('id'=>103, 'parentid'=>101, 'name'=>'a011'), | |
| array('id'=>101, 'parentid'=>100, 'name'=>'a01'), | |
| array('id'=>104, 'parentid'=>100, 'name'=>'a02'), | |
| ); | |
| $tree = createTree($a, $a[0]); | |
| print_r($tree); | |
| function createTree(array $a, array $root): array { | |
| $leaf = [ | |
| 'id' => $root['id'], | |
| 'name' => $root['name'], | |
| 'children' => [], | |
| ]; | |
| foreach ($a as $node) { | |
| if ($node['parentid'] == $root['id']) { | |
| $leaf['children'][] = createTree($a, $node); | |
| } | |
| } | |
| return $leaf; | |
| } | |
Author
meysampg
commented
Apr 27, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment