There is a one-dimensional array. The ascending order is configured. How to make a ul tree type nested list?

screenshot

That is, the most important parent is transport, then a child of passenger cars and the last child is mercedes

  • 2
    this is not a tree view, the element of the tree must either have a parent index, or the parent has a list of children, otherwise you will not be able to make a tree. What you have is a linear tree with no descendants - Vasily Barbashev
  • Does the crystal ball suggest that the array continues? [3] => Транспорт , [4] => Грузовые авто , [5] => Камаз , and so on, three each? And the array is long, and its task is to run through it all, and disassemble it into a tree, where in the root “Transport” will be only once? - Sergiks

2 answers 2

Perhaps the author wants something like this:

 $a = [ 0 => [ 'title' => 'Транспорт', 'values' => [ 0 => [ 'title' => 'Легковые', 'values' => [ 0 => ['title' => 'car1'], 1 => ['title' => 'car2'], ], ], ], ] ]; function echoUl($tree) { echo "<ul>" foreach ($tree as $value) { echo "<li>"; echo "<b>" . $value['title'] . "</b><br/>"; if (isset($value['values'])) { echoUl($value['values']); } echo "</li>"; } echo "</ul>"; } echoUl($a); 

I assume that a one-dimensional array should be converted into a tree.

     $a = [ 'transport', 'cars', 'mers' ]; foreach( $a as $b ) { echo "<ul><li>$b"; } $i = count($a); while( $i-- ) { echo '</li></ul>'; } 

    But something tells me that it is not really necessary.

    • and what will you do? <ul> <li> transport <ul> <li> cars <ul> <li> mers </ li> </ ul> </ li> </ ul> </ li> </ ul> - EatMyDust
    • one
      Exactly. Exactly what ordered in the question. BTW, was it possible to read the last phrase in the answer? - PinkTux
    • If you believe the crystal ball, then yes, that's right - EatMyDust
    • won't while ($ i--) be an infinite loop? - Boris Begun
    • @BerezhimovBoris, why would? However, self-testing takes a few seconds. - PinkTux