Re: array recursion from database rows
| From: | Chris W | Date: | Sun, 25 May 2008 01:40:42 +0000 |
| Subject: | Re: array recursion from database rows | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-274671@lists.php.net to get a copy of this message | ||
Bob wrote:
Hi. I have a database table I have created for navigation. The table fields are uid, parent_id, menu_name. Each entry is either a top level element with a parent_id of 0 or a child which has a parent_id that relates to the parent uid. What I am trying to do is recurse through a set of rows adding the child(ren) of a parent to a multi-dimensional array. Does anyone know how I can do this, I've tried (unsuccessfully) to traverse the rows to create this array but I keep failing miserably. This is probably very easy for the people on this list so I am hoping someone could help me out.I recently wrote a function to do just that. My data structure is a little different than yours. My table is called menuitems and is designed to store menu items for many different menus. But I do use the same ParentID concept you described to link sub menus in. I just call my function recessively. Here is a slightly simplified version of my function. I replaced the standard html tags with [ and ] to avoid stupid email clients trying to encode it as an html message. function PrintMenu($MenuID, $ParentItemID) { $query = "SELECT * \n"; $query .= "FROM
menuitem \n";
$query .= "WHERE MenuID = '$MenuID' AND ParentItemID = '$ParentItemID' \n";
$query .= "ORDER BY OrderBy \n";
//print "[pre>$query[/pre>\n";
$result = mysql_query($query);
QueryErrorLog($result, $query, __FILE__, __LINE__, __FUNCTION__, mysql_error(), mysql_errno(), 1);
if(mysql_num_rows($result) > 0){
print "[ul]\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
foreach($row as $TmpVar => $TmpValue){
$$TmpVar = $TmpValue;
}
print "[li][a href='$URL']$Title[/a][/li]\n";
PrintMenu($MenuID, $MenuItemID);
}
print "[/ul]\n";
}
}
--
Chris W
KE5GIX
"Protect your digital freedom and privacy, eliminate DRM,
learn more at http://www.defectivebydesign.org/what_is_drm"
Ham Radio Repeater Database.
http://hrrdb.com