Last active
November 13, 2019 07:36
-
-
Save beephotography/1471f1cba6b3a35fd137507e2a824629 to your computer and use it in GitHub Desktop.
Converts a flat array to a tree structure with references
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 array $navigation | |
* @return array | |
*/ | |
private function flatArrayToTree(array $navigation): array | |
{ | |
$navigationTree = []; | |
foreach ($navigation as $nav) { | |
$navigationTree[$nav['id']] = $nav; | |
} | |
foreach ($navigationTree as &$nav) { | |
if (false === isset($nav['children'])) { | |
$nav['children'] = []; | |
} | |
// Do not add root node | |
if (null === $nav['parentId'] || false === isset($navigationTree[$nav['parentId']])) { | |
continue; | |
} | |
if (false === array_key_exists('children', $navigationTree[$nav['parentId']])) { | |
$navigationTree[$nav['parentId']]['children'] = []; | |
} | |
$navigationTree[$nav['parentId']]['children'][$nav['url']] = &$nav; | |
} | |
return $navigationTree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment