Advertisement
Guest User

build tree from array of instances

a guest
Sep 17th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.65 KB | None | 0 0
  1. function buildTree($flat, $pidKey, $idKey = null) {
  2.     $grouped = array();
  3.     foreach ($flat as $sub) {
  4.         $sub->depth = 0;
  5.         $grouped[$sub->{$pidKey}][] = $sub;
  6.     }
  7.  
  8.     $fnBuilder = function ($siblings, $depth) use (&$fnBuilder, $grouped, $idKey) {
  9.         foreach ($siblings as $k => $sibling) {
  10.             $id = $sibling->{$idKey};
  11.             $sibling->depth = $depth;
  12.             if (isset($grouped[$id])) {
  13.                 $sibling->children = $fnBuilder($grouped[$id], $depth + 1);
  14.             }
  15.             $siblings[$k] = $sibling;
  16.         }
  17.  
  18.         return $siblings;
  19.     };
  20.  
  21.     return $fnBuilder($grouped[0], 0);
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement