Answer the question
In order to leave comments, you need to log in
How to make a tree view in Yii2?
Hello!
There is a DB with categories. There are both main categories and subcategories.
Example :
- Movies (id=1, parent_id=0)
------ Science Fiction (id=3, parent_id=1)
------ Horror (id=4, parent_id=1)
- Series (id= 2, parent_id=0)
It turned out to display a list of categories of this kind:
- Movies (id=1, parent_id=0)
- Series (id=2, parent_id=0)
- Science Fiction (id=3, parent_id=1)
- Horror (id =4, parent_id=1)
And you need to make sure that the subcategories are under the main categories.
Sorting by id and without nesting.
I hope that I clearly painted the essence of what is needed. Thank you in advance.
Answer the question
In order to leave comments, you need to log in
class Menu extends ActiveRecord
{
// ...
public static function getList()
{
$data = static::find()
->select(['id', 'parent_id', 'title'])
->orderBy('parent_id ASC')
->asArray()
->all();
$sort = new SortList([
'data' => $data,
'prefix' => '------',
]);
$sortList = ArrayHelper::map($sort->getList(), 'id', 'title');
return $sortList;
}
}
class SortList extends Object
{
public $data;
public $prefix = ' ';
protected function getPath($category_id, $prefix = false)
{
foreach ($this->data as $item) {
if ($category_id == $item['id']) {
$prefix = $prefix ? $this->prefix . $prefix : $item['title'];
if ($item['parent_id']) {
return $this->getPath($item['parent_id'], $prefix);
} else {
return $prefix;
}
}
}
return '';
}
public function getList($parent_id = 0)
{
$data = [];
foreach ($this->data as $item) {
if ($parent_id == $item['parent_id']) {
$data[] = [
'id' => $item['id'],
'title' => $this->getPath($item['id'])
];
$data = array_merge($data, $this->getList($item['id']));
}
}
return $data;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question