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

后端 未结 8 617
栀梦
栀梦 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:07

    My final solution (thanks to Starx and varan):

    function toSelect ($arr, $depth=0) {    
        $html = '';
        foreach ( $arr as $v ) {
    
            $html.= '' . PHP_EOL;
    
            if ( array_key_exists('children', $v) ) {
                $html.= toSelect($v['children'], $depth+1);
            }
        }
    
        return $html;
    }
    
    echo '';
    

    Even the RecursiveIteratorIterator solution is good (thanks hakre).

提交回复
热议问题