作者:郭雪峰Rongeqw_983 | 来源:互联网 | 2023-08-25 10:34
Myfunctionlookslikethat.Itworksbutdoeslotsofwork(recursivelycallsitselfanddoeslots
My function looks like that. It works but does lots of work (recursively calls itself and does lots of db queries.). There must be another way to do same thing but with array (with one query). I can't figure out how to modify this function to get it work with array. Please help.
我的功能看起来像那样。它工作但很多工作(递归调用自身并执行大量的数据库查询。)。必须有另一种方法来做同样的事情,但使用数组(有一个查询)。我无法弄清楚如何修改此函数以使其与数组一起使用。请帮忙。
function genMenu($parent, $level, $menu, $utype) {
global $db;
$stmt=$db->prepare("select id, name FROM navigation WHERE parent = ? AND menu=? AND user_type=?") or die($db->error);
$stmt->bind_param("iii", $parent, $menu, $utype) or die($stmt->error);
$stmt->execute() or die($stmt->error);
$stmt->store_result();
/* bind variables to prepared statement */
$stmt->bind_result($id, $name) or die($stmt->error);
if ($level > 0 && $stmt->num_rows > 0) {
echo "\n\n";
}
while ($stmt->fetch()) {
echo "- ";
echo '' . $name . '';
//display this level's children
genMenu($id, $level+1, $menu, $utype);
echo "
\n\n";
}
if ($level > 0 && $stmt->num_rows > 0) {
echo "
\n";
}
$stmt->close();
}
4 个解决方案
2
You can build a tree-based array fairly easily, so it'd be one single query and then a bunch of PHP logic to do the array building:
你可以很容易地构建一个基于树的数组,所以它是一个单一的查询,然后是一堆PHP逻辑来进行数组构建:
$tree = array();
$sql = "SELECT id, parent, name FROM menu WHERE parent ... etc.... ";
$results = mysql_query($sql) or die(mysql_error());
while(list($id, $parent, $name) = mysql_fetch_assoc($results)) {
$tree[$id] = array('name' => $name, 'children' => array(), 'parent' => $parent);
if (!array_key_exists($tree[$parent]['children'][$id])) {
$tree[$parent]['children'][$id] = $id;
}
}
For this, I'm assuming that your tree has a top-level '0' node. if not, then you'll have to adjust things a bit.
为此,我假设您的树有一个顶级'0'节点。如果没有,那么你将不得不调整一下。
This'd give you a double-linked tree structure. Each node in the tree has a list of its children in the ['children']
sub-array, and each node in the tree also points to its parent via the ['parent']
attribute.
这将为您提供双链接树结构。树中的每个节点在['children']子数组中都有一个子节点列表,树中的每个节点也通过['parent']属性指向其父节点。
Given a certain starting node, you can traverse back up the tree like this:
给定一个起始节点,您可以像这样遍历树:
$cur_node = 57; // random number
$path = array();
do {
$parent = $tree[$cur_node]['parent'];
$path[] = $parent;
$cur_node = $parent;
} while ($parent != 0);