Creating an array using recursive php from mysql

后端 未结 2 1704
抹茶落季
抹茶落季 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 
    }
    
    0 讨论(0)
  • 2021-01-15 08:59

    It would probably be easiest if you created an array that mapped from id to object as you create your objects so you can easily lookup nested objects. Basically:

    $tree = array();
    $lookup = array();
    
    while($row = mysql_fetch_assoc($result))  
    {
        $object = array('id' => $row['id'],        
                        'description' => $row['description'],        
                        'parentId' => $row['parentId']);
    
        $lookup[$row['id']] = $object;
    
        $parentId = $row['parentId'];
        if ($parentId == 0)
        {
            $tree[] = $object;
        }
        else
        {
            $lookup[$parentId]['Children'][] = $object;
        }
    }
    
    0 讨论(0)
提交回复
热议问题