Display tree menu of selected parent

前端 未结 1 981
日久生厌
日久生厌 2021-01-07 08:57

Here im building a tree menu. A category is accessed by its id and its child displayed. my function works fine for two level menu but fails to generate level third. Third le

相关标签:
1条回答
  • 2021-01-07 09:08

    I see one problem with your solution. When you check for ID if($id == $record->id) you will only match the current level in the tree. i.e. selecting Dell with id=2 will not match the first iteration so your function wil not traverse to next level.

    You need to keep track of the path to your selected menu.

    In your case. When you select Dell you will only se "Computer", am I right?

    How about something like this:

    ...
      function rederTreeById($records, $path) {
            echo '<ul>';
            foreach($records as $record) {
                    if(in_array($record->id, $path)) {
                            echo '<li>'.$record->title;
                            if(!empty($record->childs)) {
                                    rederTreeById($record->childs, $path);
                            }
                            echo '</li>';
                    } else {
                            echo '<li>'.$record->title.'</li>';
                    }
            }
            echo '</ul>';
     }
    
     function getPath($id) {
        $path = array();
        $current=$id;
        $path[] = 1
        while(!is_null($categories[$current]->parent_id)) {
            $current=$categories[$current]->parent_id
            $path[] = $current;
        }
        return $path;
     }
    
    
    $selectedId = 1;
    
    
     rederTreeById($rootCategories, getPath($selectedId));
    ...
    
    0 讨论(0)
提交回复
热议问题