我想从MySQL中提取菜单项。
Main menu id=1, parentid=0
-Contact us id=2, parentid=1
-Music id=3, parentid=1
--Rock id=8, parentid=3
--Classic id=9, parentid=3
-Car id=4, parentid=1
--Toyota id=5, parentid=4,
--Ford id=6, parentid=4,
--Honda id=7, parentid=4
Other menu id=10, parentid=0
-Othermain id=11, parentid=10
--submenu id=12, parentid=11
etc.
我可以从id = 1到4中提取数据并显示“... where parentid = 1”等。 然而,这只是最高级别。
但我想拉出所有数据,包括每个菜单(主菜单)的子菜单。
有人可以告诉我如何在MySQL中编写查询吗?
提前致谢。
答案 0 :(得分:4)
您需要实现递归以重复调用数据库以检索所有子项。您将不得不用自己的数据库抽象层实现替换我的数据库抽象层实现,但概念是相同的。
function generateTree($parentid = 0, &$tree) {
$sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid);
$res = $this->db->results($sql);
if ($res) {
foreach ($res as $r) {
// push found result onto existing tree
$tree[$r->id] = $r;
// create placeholder for children
$tree[$r->id]['children'] = array();
// find any children of currently found child
$tree = generateTree($r->id, $tree[$r->id]['children']);
}
}
}
function getTree($parentid) {
// memcache implementation
$memcache = new Memcache();
$memcache->connect('localhost', 11211) or die ("Could not connect");
$tree = $memcache->get('navigation' . $parentid);
if ($tree == null) {
// need to query for tree
$tree = array();
generateTree($parentid, $tree);
// store in memcache for an hour
$memcache->set('navigation' . $parentid, $result, 0, 3600);
}
return $tree;
}
// get tree with parentid = 0
getTree(0);
function generateTree($parentid = 0, &$tree) {
$sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid);
$res = $this->db->results($sql);
if ($res) {
foreach ($res as $r) {
// push found result onto existing tree
$tree[$r->id] = $r;
// create placeholder for children
$tree[$r->id]['children'] = array();
// find any children of currently found child
$tree = generateTree($r->id, $tree[$r->id]['children']);
}
}
}
// get tree with parentid = 0
$tree = array();
$parentid = 0;
generateTree($parentid, $tree);
// output the results of your tree
var_dump($tree); die;
上述情况未经测试,如果有人发现错误,请告诉我或随时更新。
答案 1 :(得分:1)
最快的方法是从表中获取所有元素并在代码端构建菜单树。