Skip to content

Instantly share code, notes, and snippets.

@paintmeyellow
Last active November 26, 2022 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paintmeyellow/bcb5da1e3e4540ebcb5a84618f7ad581 to your computer and use it in GitHub Desktop.
Save paintmeyellow/bcb5da1e3e4540ebcb5a84618f7ad581 to your computer and use it in GitHub Desktop.
nestedSets getTree
<?php
public function getTree(): array
{
$trees = [];
$stack = [];
$categories = ...;
foreach ($categories as $category) {
$count = count($stack);
$item = $category;
$item['childs'] = [];
while ($count > 0 && $stack[$count - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$count--;
}
if ($count === 0) {
$trees[$category['id']] = $item;
$stack[] = &$trees[$category['id']];
} else {
$stack[$count - 1]['childs'][$category['id']] = $item;
$stack[] = &$stack[$count - 1]['childs'][$category['id']];
}
}
return $trees;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment