[nycphp-talk] nested set tree sorting
csnyder
chsnyder at gmail.com
Fri Aug 1 16:43:34 EDT 2008
On Thu, Jul 31, 2008 at 2:06 AM, Marc Antony Vose <suzerain at suzerain.com> wrote:
> Has anyone previously tackled this problem
> before, and have some sample code to rebuild the entire tree, but
> alphabetize or sort the entries in each level?
>
Heh, that's a nice problem.
You could write a recursive function that builds a new tree by walking
the existing one, but with everything properly alphabetized. This is
expensive, and memory could be an issue if you have a lot of
categories at high depths, but it's a straightforward approach.
You could also create a hierarchical naming scheme for the categories
( /fruit/apples, /fruit/organges, etc ) and rebuild the tree in chunks
based on name. That gets around memory limitations, but of course it
still takes time to build the new tree.
If you don't want to build a new tree each time, you'll need a way to
move the categories around arbitrarily. I can point you to my
implementation at
http://trac.dey.fcny.org/browser/fcnyl3/lib/fcnyNode.php#L505
It's a bit mind-bending, but the general idea is to move the set you
are working with out of the tree, move the nodes around (update the
left and right values) within the set, and then move the reorganized
set back into its old place in the tree.
In practice, it might not be that big a deal to leave them out of
order and use an ORDER BY clause to sort the categories at runtime.
Chris Snyder
http://chxor.chxo.com/
More information about the talk
mailing list