Creating an array using recursive php from mysql

后端 未结 2 1736
抹茶落季
抹茶落季 2021-01-15 08:42

I need to create an array from a mysql database organized like so

id    description    parentId    
1      Level 1        0           
2      Level 2                 


        
2条回答
  •  庸人自扰
    2021-01-15 08:48

    I found this code for grouping parent child arrays to be amazing. I have tested in 4 depths with no issue what so ever. It isn't a recursive function though.

    $tree = null;
    foreach($results as $result)
    {
        $thisref = &$refs->{$result['id']};
        foreach($result as $k => $v)
        {
            $thisref->{$k} = $v;
        }
        if ($result['parentId'] == 0) {
            $tree->{$result['id']} = &$thisref;
        } else {
            $refs->{$result['parentId']}->children->{$result['id']} = &$thisref;
        }
    }
    
    $tree; // contains the newly sorted tree.
    

    You may have to do some modification for it to fully work with your situation. But basically it loops through all the results and combines them by reference.

    Do note that the ending $tree data type is an object and not an array

    Good Luck

    UPDATE

    You can create the array as such

    $query = "SELECT * FROM pB_test ORDER BY parentId ASC";
    $dbresult = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
    
    $results = array();
    while($row=mysql_fetch_assoc($dbresult)) 
    { 
        $results[]=$row 
    }
    

提交回复
热议问题