How to render the contents of an array

Asked

Viewed 75 times

1

In the application, there is a menu that is represented in PHP in the form of an array:

$menu = [
    ["title" => "Home", "path" => "/home", "children" => []],
    ["title" => "Secção", "path" => "/seccao", "children" => [
        ["title" => "Secção 1", "path" => "/seccao/1", "children" => []],
        ["title" => "Secção 2", "path" => "/seccao/2", "children" => [
             ["title" => "Subsecção 2.1", "path" => "/seccao/2/1", "children" => [
                 ["title" => "Subsecção 2.1.1", "path" => "/seccao/2/1/1", "children" => [
                      ["title" => "Subsecção 2.1.1.1", "/seccao/2/1/1/1", "children" => []],
                      ["title" => "Subsecção 2.1.1.2", "/seccao/2/1/1/2", "children" => []],
                      //...
                 ]],
             ]],
        ]],
    ]],
]

The above rendered menu should look like this:

  • Home
  • Section
    -- Section 1
    -- Section 2
    ---- Subsection 2.1
    ------ Subsection 2.1.1
    -------- Subsection 2.1.1.1
    -------- Subsection 2.1.1.N

Note that in the example each existing position can have an undefined number of children.

My question is, how to render the menu the way it is in the example above using Twig?

  • 1

    Recursion is the key.

  • @Diegof I forgot to say it was using Twig, but the solution should still be recursive.

  • In that case, I always prefer an OOP. This array reminds me of Luciano Hulk ... "Madness, Madness, Madness"

  • @Wallacemaxters didn’t get it. How can OOP solve the problem? Actually this is the result that is passed to Twig and not the code itself. Each position of the array is an instance of the "menu" object, only for ease I just put an array with strings in the example, but the idea is the same.

No answers

Browser other questions tagged

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