Too many people request me this enhancement, also it should be included in 1.1 branch.
Unfortunately, I did this method AFTER Doctrine 1.1 became feature freezed, so it could not be included in distribution.
I actually didn't finish the implementation of this. It currently only deals with array-hydrated resultsets. When I was building it, I found a couple of needed changes into 1.1 that I did until the feature freeze, so the record-hydrated resultset is easy enough to accomplish too. To include the support, just use mapValue() method.
I usually create a DoctrineX_NestedSet class to support this and also other methods.
Feel free to use it as you want.
class DoctrineX_NestedSet
{ public
static function toHierarchy
($collection) { // Trees mapped $trees =
array();
$l =
0;
if (count($collection) >
0) { // Node Stack. Used to help building the hierarchy $stack =
array();
foreach ($collection as $child) { $item =
$child;
$item['__children'] =
array();
// Number of stack items $l =
count($stack);
// Check if we're dealing with different levels while ($l >
0 &&
$stack[$l -
1]['level'] >=
$item['level']) { array_pop($stack);
$l--;
} // Stack is empty (we are inspecting the root) if ($l ==
0) { // Assigning the root child $i =
count($trees);
$trees[$i] =
$item;
$stack[] = &
$trees[$i];
} else { // Add child to parent $i =
count($stack[$l -
1]['__children']);
$stack[$l -
1]['__children'][$i] =
$item;
$stack[] = &
$stack[$l -
1]['__children'][$i];
} } } return $trees;
}}
Usage:
// Just remember to ORDER BY root_id AND lft ascending and to select level column!
// ...
$rs = $q->execute($params, Doctrine::HYDRATE_ARRAY);
$trees = DoctrineX_NestedSet::toHierarchy($rs);