Answer the question
In order to leave comments, you need to log in
What is the error when building nested sets menu Yii2?
Hello. I am building a regular menu implemented on nested sets:
/**
* @param Category[] $categories
* @param int $activeId
* @param int $parent
* @return array
*/
private function getMenuItems($categories, $activeId = null, $parent = null)
{
$list = [];
foreach ($categories as $category) {
if($category->lft >= $category->id && $category->rgt >= $category->id){
$list[$category->id] = [
'active' => $activeId === $category->id,
'label' => $category->name,
'url' => ['catalog/list', 'id' => $category->id],
'items' => $category->children()->all()
];
}else{
$list[$category->id] = [
'active' => $activeId === $category->id,
'label' => $category->name,
'url' => ['catalog/list', 'id' => $category->id],
];
}
}
return $list;
}
Answer the question
In order to leave comments, you need to log in
public static function getTree($categories, $left = 0, $right = null, $lvl = 1){
$tree = [];
foreach ($categories as $index => $category) {
if ($category->lft >= $left + 1 && (is_null($right) || $category->rgt <= $right) && $category->lvl == $lvl) {
$tree[$index] = [
'id' => $category->id,
'label' => $category->name,
'url' => ['/shop/catalog/list', 'id' => $category->id],
'items' => self::getTree($categories, $category->lft, $category->rgt, $category->lvl + 1),
];
}
}
return $tree;
}
public static function getFullTreeStructure(){
$roots = Category::find()->roots()->addOrderBy('root, lft')->all();
$tree = [];
foreach ($roots as $root){
$tree [] = [
'id' => $root->id,
'label' => $root->name,
'url' => ['/shop/catalog/list', 'id' => $root->id],
'items' => self::getTree($root->children()->all()),
];
}
return $tree;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question