I am developing one e-commerce platform where admin can manage menu, category and sub-category. Now, I want display it in mega menu.
Menu1
Category1.1
SubCategory1
SubCategory2
Category1.2
SubCategory
Menu2
Category2.1
SubCategory1
This is a possible structure with I came up. I have 2 db tables - Menu, Category. In category, there is a column called sub_category
where I am storing sub category values with ,
separator.
Now, after running below query -
$data = DB::select('SELECT m.id AS mId, m.name AS menu,
m.meta_keywords AS menu_keywords, m.meta_description AS menu_description,
c.id AS cId, c.name AS category, c.sub_category, c.meta_keywords AS
category_keywords, c.meta_description AS category_description
FROM `menu` AS m LEFT JOIN `category` AS c ON c.menuId = m.id
WHERE m.is_publish = 1 AND c.is_publish = 1');
Now, I want to build a tree where I can get a result something like this -
"id" => 1,
"name" => "Fashion"
"category" => [
1 => [
"cId" => 1,
"category" => "Men"
"sub_category" => "Shirt, T-shirt"
],
2 => [
"cId" => 2,
"category" => "Women"
"sub_category" => ""
],
]
Please help me out to find out solution. Thank you in advance.
As per your db structure and requirement, you can use below function -
public function menuTree($data){
$menuId = $menu = $sub = $op = array();
foreach($data as $d){
if(in_array($d->mId, $menuId)){
$sub['cId'] = $d->cId;
$sub['category'] = $d->category;
$sub['sub_category'] = $d->sub_category;
$sub['category_keywords'] = $d->category_keywords;
$sub['category_description'] = $d->category_description;
$menu[$d->mId]['category'][] = $sub;
} else {
$menuId[] = $d->mId;
$op['id'] = $d->mId;
$op['menu'] = $d->menu;
$op['menu_keywords'] = $d->menu_keywords;
$op['menu_description'] = $d->menu_description;
$menu[$d->mId] = $op;
if($d->cId != NULL){
$sub['cId'] = $d->cId;
$sub['category'] = $d->category;
$sub['sub_category'] = $d->sub_category;
$sub['category_keywords'] = $d->category_keywords;
$sub['category_description'] = $d->category_description;
$menu[$d->mId]['category'][] = $sub;
}
}
}
return $menu;
}
Still I believe there will be a better solution. Hope this works for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.