Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement