すべての子を取得するためにデータベースを繰り返し呼び出すには、再帰を実装する必要があります。私のデータベース抽象化レイヤーの実装を独自のものに置き換える必要がありますが、概念は同じです。
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']);
}
}
}
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;
上記はテストされていないので、誰かがエラーを見つけた場合は、私に知らせてください。または、遠慮なく更新してください。