I edited Hugo's code:
MySQL's code: sqlfiddle
our table like this:
ID | Categories_name | Parent_id
our Data is(the numbers on picture, shows id categories):
our PHP codes:
<?php
$db=mysql_connect("127.0.0.1","root","");
$db_name = "test";
mysql_select_db($db_name,$db);
$query = "SELECT `id`,`cat_name`,`parent_id` FROM `categories`";
$result=mysql_query($query);
$num=mysql_num_rows($result);
$level_each_rows = array();
$rows = array();
for($i = 0 ; $i < $num ; $i++)
{
$q_data = mysql_fetch_array($result);
$rows[] = $q_data;
}
function getChildren_string($p)
{
global $rows;
global $level_each_rows;
$r = array();
$i = 0;
$return = '';
foreach($rows as $row)
{
if ($row['parent_id'] == $p)
{
if($row['parent_id'] == 0)
{
$level_each_rows[$row['id']]['i'] = 0;
}
else
{
$level_each_rows[$row['id']]['i'] = $level_each_rows[$row['parent_id']]['i'] + 1;
}
$return = $return.'
<tr>
<td>'.$row['parent_id'].'</td>
<td><div style="margin:0px '.($level_each_rows[$row['id']]['i'] * 35).'px;">['.$row['id'].'] - '.$row['cat_name'].'</div></td>
</tr>
';
$return = $return.getChildren_string($row['id']);
$i++;
}
}
//---
return $return;
}
$childs = getChildren_string(0);
echo '
<div dir="ltr">
<table dir="ltr" border="1">
<tr>
<td>Parent ID</td>
<td>Child ID</td>
</tr>
';
echo $childs;
echo '
</table>
</div>
';
?>
Result: