berlinsurfer: Nested Sets als Multidimensionales Array

Beitrag lesen

Für alle, die auf diese Seite soßen, hier die Lösung:
ihr braucht unbedingt die depth aus dem Query.
Sprich:

$sql = "SELECT node.title, node.id as id, (COUNT(parent.id) - 1) AS depth
    FROM nested_category AS node,
    nested_category AS parent
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
    GROUP BY node.id
    ORDER BY node.lft";
$res = load() // wie auch immer;
$n = _toHierarchy(&$res);

Viel Spaß damit.

function _toHierarchy(&$collection) {
    $trees = array();
    $l = 0;

if (count($collection) > 0) {
      $stack = array();
      foreach ($collection as $node) {
        $item = $node;
        $item["children"] = array();
        $l = count($stack);
        while ($l > 0 && $stack[$l-1]['depth'] >= $item['depth']) {
          array_pop($stack);
          $l--;
        }
        if ($l == 0) {
          $i = count($trees);
          $trees[$i] = $item;
          $stack[] = &$trees[$i];
        } else {
          $i = count($stack[$l-1]["children"]);
          $stack[$l-1]["children"][$i]=$item;
          $stack[]=&$stack[$l-1]["children"][$i];
        }
      }
    }
    return $trees;
  }