How can I build a nested HTML list with an infinite depth from a flat array?

前端 未结 3 906
暗喜
暗喜 2021-01-06 10:00

I\'m trying to produce a multi-level HTML list from a source array that is formatted like this:

/**
 * id = unique id
 * parent_id = \"id\" that this item is         


        
3条回答
  •  鱼传尺愫
    2021-01-06 10:17

    Print:

    function printListRecursive(&$list,$parent=0){
        $foundSome = false;
        for( $i=0,$c=count($list);$i<$c;$i++ ){
            if( $list[$i]['parent_id']==$parent ){
                if( $foundSome==false ){
                    echo '
      '; $foundSome = true; } echo '
    • '.$list[$i]['text'].'
    • '; printListRecursive($list,$list[$i]['id']); } } if( $foundSome ){ echo '
    '; } } printListRecursive($list);

    Create multidimensional array:

    function makeListRecursive(&$list,$parent=0){
        $result = array();
        for( $i=0,$c=count($list);$i<$c;$i++ ){
            if( $list[$i]['parent_id']==$parent ){
                $list[$i]['childs'] = makeListRecursive($list,$list[$i]['id']);
                $result[] = $list[$i];
            }
        }
        return $result;
    }
    
    $result = array();
    $result = makeListRecursive($list);
    echo '
    ';
    var_dump($result);
    echo '
    ';

提交回复
热议问题