An array in PHP with ID, Category and Parent
$array = Array (
[0] => Array ( [id] => 11 [catname] => ABC [parent] => 0 )
[1] => Array ( [id] => 12 [catname] => PQR [parent] => 11 )
[2] => Array ( [id] => 13 [catname] => IJK [parent] => 11 )
[3] => Array ( [id] => 14 [catname] => MNO [parent] => 11 )
[4] => Array ( [id] => 15 [catname] => STU [parent] => 11 )
[5] => Array ( [id] => 16 [catname] => XYZ [parent] => 11 )
)
The same array can be obtained by fetching data from database.
Now pass the array to the following function.
Script to generate tree.
function generateTree($array, $parent = 0, $level = 0)
{
$has_children = false;
foreach($array as $key => $value)
{
if ($value['parent'] == $parent)
{
if ($has_children === false)
{
$has_children = true;
echo '<ul>';
$level++;
}
echo '<li><a href="?id=' . $value['id'] . '">' . $value['catname'] . '</a>';
generateTree($array, $value['id'], $level);
echo '</li>';
}
}
if ($has_children === true) echo '</ul>';
}