我试图从数据库递归地获取部分的子部分。现在,我的代码只获得父母而不是孩子。我需要对此代码进行哪些修改才能实现目标?感谢名单
function getSections()
{
$this->connectToDB();
// get list of sections that has no parents
$sql ="SELECT * FROM sections WHERE parent = 0 ORDER BY id ASC";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$thisID = $row['id'];
// recursivly get childeren
$childeren = $this->recursivlyGetSections($thisID);
// add to the final result
$toReturn .= "$thisID<br>$childeren";
}
// return final result
return $toReturn;
}
答案 0 :(得分:4)
function getSections()
{
$this->connectToDB();
// get list of sections
$sql ="SELECT * FROM sections ORDER BY id ASC, parent ASC";
$result = mysql_query($sql);
$rezArray = array();
while($row=mysql_fetch_array($result))
{
if(!isset($rezArray[$row['parent']]))
$rezArray[$row['parent']] = array();
$rezArray[$row['parent']][] = $row;
}
//.. do something with the array
}
使用$rezArray
,其中所有结果按父级排序 - 而不是进行多次查询。
答案 1 :(得分:2)
如果您希望在数据库中存储完整的树结构,并且可以更频繁地读取它,那么您可能需要考虑将存储实现为嵌套集: