There are 3 tables:
store (id,name)- table of storescategory (id,parent_id,name)- table of categories of unlimited nestingstore_category_rel (id, store_id, category_id)- the link table store-> category
It is necessary to display the branch to the subcategory, which is listed in the store_category_rel table.
$id_shop=10; // id нужного магазина $cats=array(); $result=array(); function build_tree($cats,$pid,$only_parent = false){ if(is_array($cats) and isset($cats[$pid])){ $tree = '<ul>'; if($only_parent==false){ foreach($cats[$pid] as $cat){ $tree .= '<li>'.$cat['name']; $tree .= build_tree($cats,$cat['id']); $tree .= '</li>'; } }elseif(is_numeric($only_parent)){ $cat = $cats[$pid][$only_parent]; $tree .= '<li>'.$cat['name']; $tree .= build_tree($cats,$cat['id']); $tree .= '</li>'; } $tree .= '</ul>'; } else return null; return $tree; } function find_parent($tmp, $cur_id){ if($tmp[$cur_id][0]['pid']!=0){ return find_parent($tmp,$tmp[$cur_id][0]['pid']); } return (int)$tmp[$cur_id][0]['id']; } $row=$base->query("SELECT * FROM category"); foreach($row AS $row){ $cats_ID[$row['id']][] = $row; $cats[$row['pid']][$row['id']]= $row; } $row=$base->query("SELECT * FROM store_category_rel WHERE store_id='$id_shop'"); foreach($row AS $row){ $res=build_tree($cats,0,find_parent($cats_ID,$row['bsc_id'])); if(!in_array($res,$result)){ $result[]=$res; } } foreach($result AS $result){ print $result; } An example of how it should be: such an array is displayed from categories 
Using the link table should result in the following tree array 