Skip to content

Instantly share code, notes, and snippets.

@seniorpreacher
Created September 17, 2019 09:43
Show Gist options
  • Save seniorpreacher/64adfcf4844974b568bc84bf3056c05e to your computer and use it in GitHub Desktop.
Save seniorpreacher/64adfcf4844974b568bc84bf3056c05e to your computer and use it in GitHub Desktop.
function buildTree($flat, $pidKey, $idKey = null) {
$grouped = array();
foreach ($flat as $sub) {
$sub->depth = 0;
$grouped[$sub->{$pidKey}][] = $sub;
}
$fnBuilder = function ($siblings, $depth) use (&$fnBuilder, $grouped, $idKey) {
foreach ($siblings as $k => $sibling) {
$id = $sibling->{$idKey};
$sibling->depth = $depth;
if (isset($grouped[$id])) {
$sibling->children = $fnBuilder($grouped[$id], $depth + 1);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
return $fnBuilder($grouped[0], 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment