您需要实现递归以重复调用数据库以检索所有子项。您将不得不用您自己的替换我的数据库抽象层实现,但概念是相同的。
内存缓存解决方案
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);
非 memcache 解决方案
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;
以上内容未经测试,因此如果有人发现错误,请告诉我或随时更新。