Search code examples
multidimensional-arrayphalconvolt

Multidimensional Array - How to access it in volt


ok i created a multidimensional array and stored it in articles

if i do

{{ dump(articles) }}

It returns

array(2) {
  ["Comedy"]=>
  array(3) {
    [0]=>
    string(18) "Comedy Title1"
    [1]=>
    string(57) "Comedy Title2"
    [2]=>
    string(41) "Comedy Title3"
  }
  ["Horror"]=>
  array(3) {
    [0]=>
    string(18) "Horror Title1"
    [1]=>
    string(57) "Horror Title2"
    [2]=>
    string(41) "Horror Title3"
  }
}

Now what i am trying to achieve is to loop through, print the heading and then the title for each section so:

**Comedy**
Comedy Title1
Comedy Title2
Comedy Title3

**Horror**
Horror Title1
Horror Title2
Horror Title3

However i can access the titles no problem but cannot seem to access the heading.

Heres what i have so far

{% for heading in articles %}
    {{ heading[loop.index0] }}
{% endfor %}

This returns the first value from the 1st section and the 2nd value from the 2nd section

 comedy Title1
 horror Title2

if i do

{% for heading in articles %}
    {% for title in heading %}
        {{ title }}<br />
    {% endfor %}
{% endfor %}

This returns all the titles in the correct order but without the header so:

Comedy Title1
Comedy Title2
Comedy Title3
Horror Title1
Horror Title2
Horror Title3

So thats perfect but i just need to print out the headers at the start of each array and thats what i cant figure out

I would have thought it was stored in the heading section but {{ heading }} returns an array and {{ heading[0] }} returns the first title. {{ articles }} returns an array and {{ articles[0] }} and even {{ articles[0][0] }} returns nothing

I know how to do this in regular php however i cant figure it out for volt, no doubt something simple


Solution

  • I'm not familiar with Volt, but based on doc's try touse something like:

     {% for key, heading in articles %}
       ** {{ key }} **<br />
            {% for title in heading %}
                {{ title }}<br />
            {% endfor %}
        {% endfor %}
    

    docs