Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active May 8, 2022 23:02
Show Gist options
  • Save igorbenic/bcb3f7605d14adfeadbc65109247fed4 to your computer and use it in GitHub Desktop.
Save igorbenic/bcb3f7605d14adfeadbc65109247fed4 to your computer and use it in GitHub Desktop.
Using a Recursive Function to Format Flat Arrays
<?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'
],
],
],
]
<?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'
]
]
<?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