如果树不是太大,你可以使用一些聪明的引用来简单地在PHP中构建树.
$nodeList = array();
$tree = array();
$query = mysql_query("SELECT category_id, name, parent FROM categories ORDER BY parent");
while($row = mysql_fetch_assoc($query)){
$nodeList[$row['category_id']] = array_merge($row, array('children' => array()));
}
mysql_free_result($query);
foreach ($nodeList as $nodeId => &$node) {
if (!$node['parent'] || !array_key_exists($node['parent'], $nodeList)) {
$tree[] = &$node;
} else {
$nodeList[$node['parent']]['children'][] = &$node;
}
}
unset($node);
unset($nodeList);
这将给您在$tree中的树结构与子节点在相应的子插槽中.
我们已经用相当大的树(>> 1000个项目)完成了此工作,它比在MySQL中执行递归查询更为稳定.