且构网

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

显示选定父级的树菜单

更新时间:2023-10-03 21:56:10

我看到您的解决方案有一个问题.当您检查ID if($id == $record->id)时,您将仅匹配树中的当前级别.即选择id = 2的Dell将不匹配第一次迭代,因此您的功能将不会遍历下一个级别.

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.

以您为例.当您选择Dell时,您只会选择计算机",对吗?

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