There is an array

$shop_categories = [ [ 'title' => 'Компьютеры', 'children' => [ [ 'title' => 'Ноутбуки', ], [ 'title' => 'Моноблоки', ], [ 'title' => 'Системные блоки', 'children' => [ [ 'title' => 'Tower', ], [ 'title' => 'Mini Tower', ] ] ] ] ], [ 'title' => 'Бытовая техника', 'children' => [ [ 'title' => 'Пылесосы', ], [ 'title' => 'Холодильники', ] ] ] ]; 

As with the help of a single function print_cats ($ shop_categories), the easiest way to display a tree is as follows:

Computers:

  • Laptops

  • Monoblocks

  • System blocks

    - Tower

    - Mini Tower

Appliances:

  • Vacuum cleaners

  • Refrigerators

  • foreach ($shop_categories as $category) { echo $category['title']; if ($category['children']) { print_cats($category['children']); } } foreach ($shop_categories as $category) { echo $category['title']; if ($category['children']) { print_cats($category['children']); } } - Alexey Shimansky
  • no, this will not work .. Notice: Undefined index: children in the if line ($ category ['children'] and the placement of categories is just a bar one by one. - Beginner
  • - You, what, and fingers for me will bend? - Yeah ......... it is clear that the column (although generally in a row) ..... it’s not hard to guess what you need to output to ul and li or to style it yourself .... or is it difficult do it yourself? ........ and then replace if with if (isset($category['children'])) - Alexey Shimansky
  • oh yes, if (isset ($ category ['children'])) is ok ... now everything is clear further already. Thank you) - Beginner

1 answer 1

 function print_cats($shop_categories) { echo '<ul>'; foreach ($shop_categories as $category) { echo '<li>', $category['title'], '</li>'; if (isset($category['children'])) { print_cats($category['children']); } } echo '</ul>'; } 

Check

  • thanks for this! - Beginner