Last active
May 8, 2022 23:02
-
-
Save igorbenic/bcb3f7605d14adfeadbc65109247fed4 to your computer and use it in GitHub Desktop.
Using a Recursive Function to Format Flat Arrays
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 | |
$flat_array = [ | |
[ | |
'parent' => 0, | |
'id' => 1, | |
'title' => 'Parent 1', | |
'content' => [ | |
'c12', | |
'c13' | |
], | |
'children' => [ | |
[ | |
'parent' => 1, | |
'id' => 'c12', | |
'title' => 'Child 1', | |
'content' => [ | |
'c21' | |
], | |
'children' => [ | |
[ | |
'parent' => 'c12', | |
'id' => 'c21', | |
'title' => 'Sub Child 2' | |
] | |
], | |
], | |
[ | |
'parent' => 1, | |
'id' => 'c13', | |
'title' => 'Child 2' | |
], | |
], | |
], | |
] |
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 | |
$flat_array = [ | |
[ | |
'parent' => 0, | |
'id' => 1, | |
'title' => 'Parent 1', | |
'content' => [ | |
'c12', | |
'c13' | |
] | |
], | |
[ | |
'parent' => 1, | |
'id' => 'c12', | |
'title' => 'Child 1', | |
'content' => [ | |
'c21' | |
] | |
], | |
[ | |
'parent' => 1, | |
'id' => 'c13', | |
'title' => 'Child 2' | |
], | |
[ | |
'parent' => 'c12', | |
'id' => 'c21', | |
'title' => 'Sub Child 2' | |
] | |
] |
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 | |
function unFlattenArray( $arrayItems, $parentId = 0 ) { | |
$branch = array(); | |
foreach ($arrayItems as $item) { | |
if ( $parentId === $item['parent'] ) { | |
$childrenItems = unFlattenArray( $arrayItems, $item['id'] ); | |
if ( $childrenItems ) { | |
$item['children'] = []; | |
foreach ( $childrenItems as $childItem ) { | |
$item['children'][] = $childItem; | |
} | |
} | |
$branch[] = $item; | |
} | |
} | |
return $branch; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment