热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

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 个解决方案

#1


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);

#2


1  

I think the first thing you can fix is removing the WHERE parent = ? clause and then work on the resulting query result, this will make you work a bit more in managing the result but will definitely safe you IO operations.

我认为你可以解决的第一件事就是删除WHERE parent =?子句然后处理生成的查询结果,这将使您在管理结果方面工作更多,但肯定会保护您的IO操作。

Using parts of Marc B Solution

使用Marc B Solution的部分内容

$tree = array();
$sql = "select id, parent, name FROM navigation AND menu=? AND user_type=?";
$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;
    }
}

print_r($tree);

Replace the ? with the actual values, and give that a run, what is your output?

更换 ?用实际值,并给出一个运行,你的输出是什么?

#3


1  

Maybe not what you wanted, but it is great when it comes to trees. You would have to rebuild your table and had some code to output the html, but you would have only one query. It could be worth the effort on the long run.

也许不是你想要的,但它对树木很有用。你必须重建你的表并有一些代码输出html,但你只有一个查询。从长远来看,这可能是值得的。

ie.If you have this menu

即如果你有这个菜单

# Menu hierarchy:
 - Home
 - Product
    |- Tv
    |- Radio
 - About us   

It would looks like this in the db.

它在db中看起来像这样。

+----+----------+-----------+-----+-----+
| id | menu     | parent_id | lft | rgt |
+----+----------+-----------+-----+-----+
| 1  | Home     | null      | 1   | 2   |
+----+----------+-----------+-----+-----+
| 2  | Product  | null      | 3   | 8   |
+----+----------+-----------+-----+-----+
| 3  | Tv       | 2         | 4   | 5   |
+----+----------+-----------+-----+-----+
| 4  | Radio    | 2         | 6   | 7   |
+----+----------+-----------+-----+-----+
| 5  | About us | null      | 9   | 10  |
+----+----------+-----------+-----+-----+

The data could be fetch using a similar query

可以使用类似的查询来获取数据

$select = "SELECT * FROM table_name WHERE lft BETWEEN 3 AND 8;"

To output a specific menu:

要输出特定菜单:

 - Product
    |- Tv
    |- Radio

I know its not exactly the answer your were looking for, but FYI, there are other ways to use hierarchical tree data.

我知道它不是你正在寻找的答案,但仅供参考,还有其他方法可以使用分层树数据。

Good luck.

#4


0  

I wrote in the past an ugly way but with simple SELECT:

我过去用一种丑陋的方式写了但是用简单的SELECT:

I store in text/varchar field strings like this:

我存储在text / varchar字段字符串中,如下所示:

/001
/001/001
/001/002
/002
/002/001
/002/001/001

Ignore the hebrew and look in window.aMessages array, to look how it works: http://www.inn.co.il/Forum/Forum.aspx/t394009#4715854

忽略希伯来语并查看window.aMessages数组,看看它是如何工作的:http://www.inn.co.il/Forum/Forum.aspx/t394009#4715854


推荐阅读
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 判断编码是否可立即解码的程序及电话号码一致性判断程序
    本文介绍了两个编程题目,一个是判断编码是否可立即解码的程序,另一个是判断电话号码一致性的程序。对于第一个题目,给出一组二进制编码,判断是否存在一个编码是另一个编码的前缀,如果不存在则称为可立即解码的编码。对于第二个题目,给出一些电话号码,判断是否存在一个号码是另一个号码的前缀,如果不存在则说明这些号码是一致的。两个题目的解法类似,都使用了树的数据结构来实现。 ... [详细]
  • 在加载一个第三方厂商的dll文件时,提示“找不到指定模块,加载失败”。由于缺乏必要的技术支持,百思不得期间。后来发现一个有用的工具 ... [详细]
  • Go语言实现堆排序的详细教程
    本文主要介绍了Go语言实现堆排序的详细教程,包括大根堆的定义和完全二叉树的概念。通过图解和算法描述,详细介绍了堆排序的实现过程。堆排序是一种效率很高的排序算法,时间复杂度为O(nlgn)。阅读本文大约需要15分钟。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 本文介绍了使用Python编写购物程序的实现步骤和代码示例。程序启动后,用户需要输入工资,并打印商品列表。用户可以根据商品编号选择购买商品,程序会检测余额是否充足,如果充足则直接扣款,否则提醒用户。用户可以随时退出程序,在退出时打印已购买商品的数量和余额。附带了完整的代码示例。 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • Java编程实现邻接矩阵表示稠密图的方法及实现类介绍
    本文介绍了Java编程如何实现邻接矩阵表示稠密图的方法,通过一个名为AMWGraph.java的类来构造邻接矩阵表示的图,并提供了插入结点、插入边、获取邻接结点等功能。通过使用二维数组来表示结点之间的关系,并通过元素的值来表示权值的大小,实现了稠密图的表示和操作。对于对稠密图的表示和操作感兴趣的读者可以参考本文。 ... [详细]
  • 本文介绍了在go语言中利用(*interface{})(nil)传递参数类型的原理及应用。通过分析Martini框架中的injector类型的声明,解释了values映射表的作用以及parent Injector的含义。同时,讨论了该技术在实际开发中的应用场景。 ... [详细]
  • 本文介绍了一道经典的状态压缩题目——关灯问题2,并提供了解决该问题的算法思路。通过使用二进制表示灯的状态,并枚举所有可能的状态,可以求解出最少按按钮的次数,从而将所有灯关掉。本文还对状压和位运算进行了解释,并指出了该方法的适用性和局限性。 ... [详细]
  • 本文介绍了在实现了System.Collections.Generic.IDictionary接口的泛型字典类中如何使用foreach循环来枚举字典中的键值对。同时还讨论了非泛型字典类和泛型字典类在foreach循环中使用的不同类型,以及使用KeyValuePair类型在foreach循环中枚举泛型字典类的优势。阅读本文可以帮助您更好地理解泛型字典类的使用和性能优化。 ... [详细]
  • 1Lock与ReadWriteLock1.1LockpublicinterfaceLock{voidlock();voidlockInterruptibl ... [详细]
  • 文章目录题目:二叉搜索树中的两个节点被错误地交换。基本思想1:中序遍历题目:二叉搜索树中的两个节点被错误地交换。请在不改变其结构的情况下 ... [详细]
  • 二叉树的前序遍历(递归版):publicArrayList<Integer> ... [详细]
author-avatar
郭雪峰Rongeqw_983
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有