Con questa versione alternativa fai una sola query ed elabori i dati in PHP (limitare il numero di query da' grossi vantaggi in termini di prestazioni):
Codice PHP:
<?php
$sql = 'SELECT id, parent, name
FROM tree';
$result = mysql_query($sql);
$data = array();
while ( $row = mysql_fetch_object($result) ) {
if ( $row->parent == 0 ) {
$root = $row->id;
} else {
$data[$row->parent][$row->id] = $row->name;
}
}
function build_tree($main, $root) {
$current = array();
foreach ( $main[$root] as $id => $name ) {
if ( isset($main[$id]) ) {
$current[$id] = array(
'name' => $name,
'children' => build_tree($main, $id),
);
} else {
$current[$id] = array(
'name' => $name,
);
}
}
return $current;
}
function print_tree($tree) {
echo "<ul>";
foreach ( $tree as $branch ) {
echo "[*]{$branch['name']}\n";
if ( !empty($branch['children']) ) {
print_tree($branch['children']);
}
}
echo "[/list]\n";
}
$tree = build_tree($data, $root);
print_tree($tree);