On the Internet, I found: the MySQL category tree and the PHP recursive function. I did the same, but I have the entire list in a row vertically.
rfr How to customize styles for this script? And to make an accordion for him to click on the parent list, the child opened. And close the previous open child lists.

// подключаемся к базе данных // делаем выборку из таблицы категорий $result = mysql_query ("SELECT `id`, `parent_id`, `name` FROM `category`"); $cats = array(); // тут будет наш массив с категориями каталога // в цикле формируем нужный нам массив while($cat = mysql_fetch_assoc($result)) $cats[$cat['parent_id']][] = $cat; // далее наша главная, рекурсивная функция, которая сформирует дерево категорий function create_tree ($cats,$parent_id){ if(is_array($cats) and isset($cats[$parent_id])){ $tree = '<ul>'; foreach($cats[$parent_id] as $cat){ $tree .= "<li><a href='view_cat.php?cat=".$cat['id']."'>".$cat['name']."</a>"; $tree .= create_tree ($cats,$cat['id']); $tree .= '</li>'; } $tree .= '</ul>'; } else return null; return $tree; } // вызываем функцию и строим дерево echo create_tree ($cats, 0); 

For example, this is the style enter image description here

enter image description here

  • 2
    it’s not quite clear what the problem is to set up styles for it, could you describe the problem in more detail? - webDev_
  • @webDev_ so I fixed it. Yes, I need to prescribe styles for him. Started but something without the result but. An example laid out too. And the accordion for him, too, as it is necessary to prescribe - Eugene

1 answer 1

 (function(){subList = function() { var e = document.querySelectorAll('.sublist'); for (var i=0;i<e.length;i++) { var ee = e[i].querySelectorAll('span'); for (var ii=0;ii<ee.length;ii++) { if (e[i].className.match(/counter/)) { var c = document.createElement('i'); c.innerText=ee[ii].parentNode.querySelector('ul').children.length; ee[ii].appendChild(c); } ee[ii].addEventListener('click',(function(e,p){return function(){ if (!e.className) { var el = e.parentNode.querySelectorAll('.show'); if (el.length) { for (var i=0;i<el.length;i++) { el[i].className = ''; if (i==el.length-1) { e.className = 'show'; } } }else{ e.className = 'show'; } }else{ e.className = ''; } }})(ee[ii].parentNode,e[i]),false); } } }})(); window.onload = function(){subList()}; 
 ul.sublist { user-select: none; -o-user-select: none; -ms-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; } ul.sublist, ul.sublist ul { list-style: none; padding: 0px; margin: 0px; display: inline-block; } ul.sublist ul { margin-left: 12px; margin-top: 6px; margin-bottom: 6px; transition: .15s margin-top; } ul.sublist li { padding: 0px; margin: 0px; } ul.sublist > li ul { display: none; } ul.sublist li.show > ul { display: block !important; } ul.sublist li > span > i { position: absolute; right: 0px; top: 0px; width: 34px; padding-top: 8px; padding-bottom: 8px; text-align: center; border-left: 1px solid rgba(0,0,0,.2); font-style: normal; margin-left: 50px; } ul.sublist li > span, ul.sublist li > a { position: relative; text-decoration: none; background-color: rgba(0,0,0,.025); display: inline-block; padding: 8px; cursor: pointer; border-left: 1px solid rgba(0,0,0,.2); border-bottom: 1px solid rgba(0,0,0,.2); min-width: 200px; color: rgba(0,0,0,.9); transition: .15s padding-left, .15s background-color; } ul.sublist.counter li > span { padding-right: 43px; } ul.sublist li:last-child > span, ul.sublist li:last-child > a { border-bottom: none; } ul.sublist li > span:hover, ul.sublist li > a:hover { background-color: rgba(0,0,0,.1); padding-left: 10px; } 
 <ul class="sublist counter"> <li> <span>Гризли</span> <ul> <li> <a href="#">Взгляд гризли</a> </li> <li> <a href="#">Отточенный клык</a> </li> <li> <a href="#">Гризли программист</a> </li> </ul> </li> <li> <span>Для дома</span> <ul> <li> <span>Мебель</span> <ul> <li> <a href="#">Жёлтый</a> </li> <li> <a href="#">Попугай</a> </li> <li> <a href="#">Ламинированный кот</a> </li> </ul> </li> <li> <span>Атмосфера</span> <ul> <li> <a href="#">Бьющаяся</a> </li> <li> <a href="#">Небьющаяся</a> </li> <li> <a href="#">Инопланетная</a> </li> </ul> </li> <li> <span>Растения</span> <ul> <li> <span>Эволюционирующие</span> <ul> <li> <a href="#">Серьёзно?</a> </li> </ul> </li> </ul> </li> </ul> </li> <li> <span>Список</span> <ul> <li> <span>Длинный</span> <ul> <li> <span>Очень</span> <ul> <li> <span>Очень</span> <ul> <li> <span>Хотя</span> <ul> <li> <a href="#">Не очень</a> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> <li> <span>Услуги</span> <ul> <li> <a href="#">Кофе с печенками</a> </li> <li> <a href="#">Похвалить код</a> </li> <li> <span>Классика</span> <ul> <li> <a href="#">Починка утюга</a> </li> </ul> </li> </ul> </li> <li> <span>Животные</span> <ul> <li> <a href="#">Hello world!</a> </li> <li> <a href="#">Твой код</a> </li> <li> <a href="#">Педаль велосипеда</a> </li> </ul> </li> <li> <span>Электроника</span> <ul> <li> <a href="#">Без комментариев</a> </li> </ul> </li> </ul> 

Hide the counter by removing the class counter

 $result = mysql_query ("SELECT `id`, `parent_id`, `name` FROM `category`"); $cats = array(); while($cat = mysql_fetch_assoc($result)) $cats[$cat['parent_id']][] = $cat; function create_tree ($cats,$parent_id){ if(is_array($cats) and isset($cats[$parent_id])){ $tree = !$parent_id?'':'<ul>'; foreach($cats[$parent_id] as $cat){ $tree .= "<li>"; $tree .= !isset($cats[$cat['id']])?"<a href='view_cat.php?cat=".$cat['id']."'>".$cat['name']."</a>":"<span>".$cat['name']."</span>"; $tree .= create_tree($cats,$cat['id']); $tree .= '</li>'; } $tree .= !$parent_id?'':'</ul>'; }else return null; return !$parent_id?'<ul class="sublist counter">'.$tree.'</ul>':$tree; } echo create_tree($cats, 0); 
  • Looked at your example, yes what you need Could you connect with my code ??. Something I can not. - Eugene
  • @ Eugene to solve another problem, create a new question in order to save a couple of question and answer. Remember to accept the answer above if it solves your problem. - webDev_
  • I apologize, I have just written how to set up styles for this script (which I wrote above, I think it’s not worth writing a new question for your script and mine :) - Eugene
  • From the beginning I did not understand the logic of the code, you are right. I'll edit in response. - webDev_
  • one
    thank you very much) God bless you :) - Eugene