Creating an array using recursive php from mysql

后端 未结 2 1705
抹茶落季
抹茶落季 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: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;
        }
    }
    

提交回复
热议问题