Categories and subcategories in a single SELECT

Asked

Viewed 270 times

0

I have the following table structure:

CATEGORIAS
id
titulo

SUBCATEGORIAS
id
id_categoria
titulo

I was wondering if there is a way to bring all categories and subcategories at once into a single select in the form of a two-dimensional array more or less as follows:

$categorias = array(
   [0] => array(
      ['id'] => 1,
      ['titulo'] => "Categoria 1",
      ['subcategorias'] => array(
         [0] => array(
            ['id'] => 1,
            ['titulo'] => "Subcategoria A"
         ),
         [1] => array(
            ['id'] => 2,
            ['titulo'] => "Subcategoria B"
         ),
         [2] => array(
            ['id'] => 3,
            ['titulo'] => "Subcategoria C"
         )
      )
   ),
   [...] <= E assim por diante...
)

Note: I use PHP with PDO.

  • from what I understand, just make a join of the two tables to bring everything in a single select

  • The problem is that in this way it brings the repeated categories.

  • 1

    yes, the result is not multidimensional, you need to assemble the json structure... you can also return the result of the subcategories as if it were a list, separated by comma for example, this helps?

  • I think it is impossible to do in only step I solved it with feature within php =/

  • to make the menus inside php I ended up using https://github.com/edomaru/codeigniter_multilevel_menu

  • @Ricardopunctual as it would be to separate by comma?

  • 1

    with a single select will generate repetition even after the relationship is 1 -> n. Then best way would be to use a select and then work the result in the code (in your case with PHP)

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.