dongwuxie7976 2011-11-21 20:32
浏览 43
已采纳

在PHP中使用数组而不是大量的数据库查询

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.

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 "
<ul>
";
    }
    while ($stmt->fetch()) {
        echo "<li>";
        echo '<a href="?page=' . $id . '">' . $name . '</a>';
        //display this level's children
        genMenu($id, $level+1, $menu, $utype);
        echo "</li>

";
    }
    if ($level > 0 && $stmt->num_rows > 0) {
        echo "</ul>
";
    }
    $stmt->close();
}
  • 写回答

4条回答 默认 最新

  • douwei9759 2011-11-21 20:47
    关注

    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:

    $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.

    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.

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题