Skip to content

Instantly share code, notes, and snippets.

@beephotography
Last active November 13, 2019 07:36
Show Gist options
  • Save beephotography/1471f1cba6b3a35fd137507e2a824629 to your computer and use it in GitHub Desktop.
Save beephotography/1471f1cba6b3a35fd137507e2a824629 to your computer and use it in GitHub Desktop.
Converts a flat array to a tree structure with references
<?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