What I am trying to do is create a string (an array of arrays) to pass to a function that uses GD to draw a hierarchical diagram (like an org chart). I have a mysql table that stores the parent and child relationships like this:
OBJECT_NAME | CHILD_NAME
----------- | -----------
Node1 | Child1
Node1 | Child2
Node1 | Child3
Child1 | GrandChild1
Child1 | GrandChild2
Child1 | GrandChild3
Child2 | GrandChild4
Child3 | GrandChild5
Child3 | GrandChild6
Basically, what I have done so far is created a recursive function that will start at Node1, get Child1 as its first child, then go back to the table to get Child1's children. This is where I run into problems. I then need to go back to Node1 and get Child2 as its second child, and then GrandChild4 as Child2's child, but I'm lost as to a way to keep track of all of this.
My script will be called each time someone accesses the page and the table entries can change from one time to the next, so I never know how many levels deep I will need to go, or how many children each object will have. The only constant is that Node1 will always exist as the root node. Keep in mind that the example given is extremely simplified. (The actual table contains over 100 entries.)
Here is an example of the string that I need to build, based on the data above:
Array('Node1'=>Array('Child1'=>Array('GrandChild1','GrandChild2',GrandChild3),'Child2'=>Array('GrandChild4'),Child3=>Array('GrandChild5','GrandChild6)))
Here is what I have so far:
<?
global $arr;
$object = 'Node1';
$arr = "Array('Node1'";
get_children($object,$arr);
function get_children($object,$arr)
{
$i = 0;
$find_children_query = "SELECT OBJECT_NAME, CHILD_NAME FROM DATA WHERE Object = '" . $object . "'";
$find_children_result = mysql_query($find_children_query) or die("<b>Error: </b>" .
mysql_error() . "<br><br><b>Please contact the system administrator.</b>");
$find_children_num_rows = mysql_num_rows($find_children_result);
while ($find_children_num_rows > 0)
{
$arr.= "=>Array";
while ($child = mysql_fetch_assoc($find_children_result))
{
if ($i == 0)
{
$arr.= "(";
}
else
{
$arr.= ",";
}
$arr.= "'" . $child['CHILD_NAME'] . "'";
$i++;
get_children($child['CHILD_NAME'],$arr);
}
$arr.= ")";
}
}
?>
Also, if anyone knows of a way to do this with an array so that I don't make so many calls to the database, please share.
Thanks,
Luke