>Subject: [PHP] Recursive Childs
<snip>
> like hotscripts.com too, so i thought if someone could tell me how to use
get all the children :
>
> ID | NAME | PARENT
> 1 X 0
> 2 Y 1
> 3 Z 2
> 4 A 2
> 5 F 1
> 6 G 5
> if i want to get all children of 1, i want to get 2, 3, 4, 5, 6!
>
> how do i get this, thanks!
>
Hi Natasha,
As your subject implies, the way to do this is with a recursive function
call. Assuming your data is in a PostgreSQL database table, you could use
something like the following (*untested* -- modify as required if you are
using MySQL or something else)
Hope this helps!
Joe
*************************************************
<?PHP
function getChildren($conn,$parent,$level,&$currentrecord,&$rowclr)
{
$level += 1;
$levelpad = "";
for($counter = 0; $counter < $level - 1; $counter++)
{
$levelpad = $levelpad . "->";
}
$levelpad = $levelpad . "";
If (! empty($parent))
{
$sql = "select id, name, parent from mytable where parent =$parent order by id";
$rs = pg_exec($conn,$sql);
for ($row = 0; $row <= pg_numrows($rs) - 1; $row++)
{
$currentrecord += 1;
if ($rowclr == "#d7d7d7")
{
$rowclr = "#ffffff";
}
else
{
$rowclr = "#d7d7d7";
}
for ($field = 0; $field <= pg_numfields($rs) - 1; $field++)
{
$rsf[pg_fieldname($rs,$field)] = pg_result($rs,$row,$field);
}
print("<tr bgcolor=\"" . $rowclr . "\">\n");
print("<td align=\"left\">" . $levelpad . $rsf["id"] . " </td>\n");
print("<td align=\"left\">" . $rsf["name"] . " </td>\n");
print("<td align=\"center\">" . $level . " </td>\n");
print("</tr>\n");
$newparent = $rsf["parent"];
getChildren($conn,$newparent,$level,$currentrecord,$rowclr);
};
pg_freeresult($rs);
}
else
{
print("<h3>No information found.</h3>\n");
}
}
$conn = pg_connect("dbname=mydb user=postgres");
$parent = 0;
$level = 0;
$currentrecord = 0;
$rowclr = "#e7e7e7";
print("<HTML><BODY>\n");
print("<table cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">\n");
print("<tr bgcolor=\"#BBBBBB\">\n");
print("<th align=\"left\">ID</th>\n");
print("<th align=\"left\">Name</th>\n");
print("<th align=\"center\">Level</th>\n");
print("</tr>\n");
getChildren($conn,$parent,$level,$currentrecord,$rowclr);
print("</TABLE>\n");
if ($currentrecord == 0)
{
print("<H3>No matches found.</H3>\n");
}
print("</BODY></HTML>\n");
?>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]