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

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

    You could pass the length to the function and increment it when you call recursively and then use the variable $length to determine the depth

    function toUL ($arr, $length = 0) {
    
        $html = '
      ' . PHP_EOL; foreach ( $arr as $v ) { $html.= '
    • ' . $v['name'] . '
    • ' . PHP_EOL; if ( array_key_exists('children', $v) ) { $html.= toUL($v['children'], $length++); } } $html.= '
    ' . PHP_EOL; return $html; }

    This is what i do usually to keep track of recursion depth and it usually get the job done

提交回复
热议问题