A drop-down list is displayed from the database, but it is impossible to structure it, display all models in a column. enter image description here

<select id="select" onchange="Change(this);"> <optgroup> <?php foreach($cat as $key => $item): ?> <?php if(count($item) > 1): // если это родительская категория ?> <option> <h3><li><a href="#"><?=$item[0]?></a></li></h3> <ul> <?php foreach($item['sub'] as $key => $sub): ?> <li>- <a href="?view=cat&amp;category=<?=$key?>"><?=$sub?></a></li> <?php endforeach; ?> </ul> </option> <?php elseif($item[0]): // если самостоятельная категория ?> <li><a href="?view=cat&amp;category=<?=$key?>"><?=$item[0]?></a></li> <?php endif; ?> <?php endforeach; ?> <optgroup> </select> 
  • For the first time I see Html markup added to option . Is it even legal? - u_mulder

1 answer 1

If you understand correctly. Not tested, but the essence should be clear

 <select id="select" onchange="Change(this);"> <optgroup> <?php foreach($cat as $key => $item): ?> <?php if(count($item) > 1): // если это родительская категория ?> <option><a href="#"><?=$item[0]?></option> //родитель <?php foreach($item['sub'] as $key => $sub): ?> <option><a href="?view=cat&amp;category=<?=$key?>">- <?=$sub?></a></option> <?php endforeach; ?> <?php elseif($item[0]): // если самостоятельная категория ?> <option><a href="?view=cat&amp;category=<?=$key?>"><?=$item[0]?> </a></option> // самостоятельная <?php endif; ?> <?php endforeach; ?> <optgroup> </select> 

In general, it is better to look towards the output of the tree using recursion.

Example

 $traverse = function ($categories, $prefix = '-') use (&$traverse) { foreach ($categories as $category) { echo PHP_EOL.$prefix.' '.$category->name; $traverse($category->children, $prefix.'-'); } }; $traverse($nodes); 

It turns out:

 - Root -- Child 1 --- Sub child 1 -- Child 2 - Another root