There are many solutions to reduce overhead. But, not knowing what your limitations are, it's hard to recommend an approach.
eg:.
use adjacency model - see my comment on dnagirl answer
load all the data into PHP and then use the recursion algorithm to create a nested tree (this will be pretty slow and will benefit from some caching)
write a recursive stored procedure that returns a result set sorted by tree of depth tree
Example 2 is a bit closer to the code .... something like ....
function build_tree(&$unsorted, $start_node) { $out=array(); foreach($unsorted as $key=>$node) { if ($node['parent']==$start_node) { $node['children']=build_tree($unsorted, $key); unset($unsorted[$key]); $out[]=$node; } } return $out; } $threaded_tree=build_tree($list_of_nodes, 0);
source share