开发者

PHP recursively get all sections

开发者 https://www.devze.com 2023-03-16 11:37 出处:网络
I am trying to get the sub-sections of sections recursively from the database. Right now, my code only gets the parents but not the children though. What modification do I have to do to this code to a

I am trying to get the sub-sections of sections recursively from the database. Right now, my code only gets the parents but not the children though. What modification do I have to do to this code to accomplish my goal? Thanx

    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 fina开发者_JAVA技巧l result
    return $toReturn;
}


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
}

Use $rezArray which has all the results sorted by parent -- instead of doing multiple queries.


If you're wanting to store a full tree structure in your database, and it is read from more often that it is written to, you might want to consider implementing the storage as a nested set:

http://en.wikipedia.org/wiki/Nested_set_model

0

精彩评论

暂无评论...
验证码 换一张
取 消