How to recursively build a <select> with unknown tree depth

后端 未结 8 600
栀梦
栀梦 2020-12-15 01:49

I have a MySQL table with a tree data structure. The fields are _id, name and parentId. When the record hasn\'t a parent, parent

相关标签:
8条回答
  • 2020-12-15 02:27

    Hi Guys you could do something like this: I have this object for the $tree:

       Array
    (
        [0] => stdClass Object
            (
                [id] => 1
                [nombre] => Category 1
                [subcategorias] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 4
                                [nombre] => Category 1.1
                            )
    
                    )
    
            )
    
        [1] => stdClass Object
            (
                [id] => 2
                [nombre] => Category 2
            )
    
        [2] => stdClass Object
            (
                [id] => 3
                [nombre] => Category 3
                [subcategorias] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 5
                                [nombre] => Category 3.1
                                [subcategorias] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [id] => 6
                                                [nombre] => Category 3.1.1
                                            )
    
                                    )
    
                            )
    
                    )
    
            )
    
    )
    

    Then Here is how to create the array for the HTML select:

        $tree=array();// PUT HERE YOUR TREE ARRAY
        $arrayiter = new RecursiveArrayIterator($tree);
        $iteriter = new RecursiveIteratorIterator($arrayiter);
        $lista=array();
        $i=0;
        foreach ($iteriter as $key => $value) 
        {
            $id=$iteriter->current();
            $iteriter->next();
            $nivel=$iteriter->getDepth();
            $nombre=str_repeat('-',$nivel-1).$iteriter->current();
            $lista[$id]=$nombre;
        }
    

    You will get something like this:

        Array
    (
        [1] => Category 1
        [4] => --Category 1.1
        [2] => Category 2
        [3] => Category 3
        [5] => --Category 3.1
        [6] => ----Category 3.1.1
    )
    

    Then you just need to create the options for the select with a simple foreach.

    0 讨论(0)
  • 2020-12-15 02:27
    function toUL ($arr, $depth = 0) {
    //    ...
    $html .= toUL($v['children'], $depth+1);
    
    0 讨论(0)
提交回复
热议问题