且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

显示所选父级的树形菜单

更新时间:2023-11-30 10:27:40

我发现您的解决方案存在一个问题.当您检查 ID if($id == $record->id) 时,您将只匹配树中的当前级别.即选择 id=2 的戴尔将与第一次迭代不匹配,因此您的函数不会遍历到下一个级别.

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?

这样的事情怎么样:

...
  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));
...