hi i have a database table , i want to set that as a tree structure and get the leaf nodes of that tree .
Recursive function can help you to generate parent/child tree. Find below link for more detail:
http://psoug.org/snippet/Recursive_function_to_generate_a_parentchild_tree_338.htm
In response to Chauhan's linked article, I'd like to post a much simpler solution:
// sample data (from one big query selecting them in one go)
$rows = array(
array('id' => 971, 'parent_id' => 3, 'label' => 'Genres'),
array('id' => 972, 'parent_id' => 3, 'label' => 'Movie Stars'),
array('id' => 1, 'parent_id' => 0, 'label' => 'Fashion'),
array('id' => 32, 'parent_id' => 1, 'label' => 'Men\'s Clothing'),
array('id' => 45, 'parent_id' => 32, 'label' => 'Couture'),
array('id' => 55, 'parent_id' => 32, 'label' => 'Denims'),
array('id' => 2, 'parent_id' => 0, 'label' => 'Music'),
array('id' => 970, 'parent_id' => 2, 'label' => 'Artists'),
array('id' => 1118, 'parent_id' => 970, 'label' => 'African'),
array('id' => 1119, 'parent_id' => 970, 'label' => 'Afrobeat'),
);
// build map and collect ids
$map = array();
$ids = array();
foreach ($rows as $row) { // one could use the typical mysql_fetch_* stuff here
if (!isset($map[$row['parent_id']])) {
$map[$row['parent_id']] = array();
}
$map[$row['parent_id']][] = $row;
$ids[] = $row['id'];
}
// recursive helper display
function helper($map, $parentId = 0) {
echo '<ul>';
foreach ($map[$parentId] as $entry) {
printf('<li>[%s] %s', $entry['id'], $entry['label']);
if (isset($map[$entry['id']])) {
helper($map, $entry['id']);
}
echo '</li>';
}
echo '</ul>';
}
// create ul
helper($map);
// the leaf nodes
print_r(
array_diff($ids, array_keys($map))
);
I also like to say, that, if such database structures cannot be avoided, recursive queries is probably the worst thing to do, performance wise.