4

Im coding in twig to visualize values that I get from php and I want that the keyname of array appear above the values.

{% if user.address %}
        <tr>
            {% for address in user.address %}
                {% for parts in address %}
                    <td width="25%">
                        {{ parts }}
                    </td>  
                {%endfor%}
            {% endfor %}
        </tr>              
{% endif %}

In the part of under {% for address in user.address %} I want put ( {{address.key}} or the real sentence that is necessary to get keyname of array )

The array is like:

  -address : array:4 [▼
    "Door" => array:1 [▼
      0 => "225"
    ]
    "Street" => array:1 [▼
      0 => "Pinky street"
    ]
    "District" => array:1 [▼
      0 => "District north"
    ]
    "City" => array:1 [▼
      0 => "New York"
    ]
  ]

Edit:

Ty for the help the result is :

{% if user.address %}
        <tr>
           {% for key, address in user.address %}
                    <td width="25%">
                        {{ key }}
                    </td>
                {%endfor%}
        </tr> 
        <tr>
           {% for address in user.address %}
                {% for parts in address %}
                    <td width="25%">
                        {{ parts }}
                    </td>  
                    {%endfor%}
           {%endfor%}
        </tr>
    {% endif %}
Batichico
  • 676
  • 1
  • 6
  • 15
  • 1
    Possible duplicate of [Twig for loop and array with key](https://stackoverflow.com/questions/10299202/twig-for-loop-and-array-with-key) – a_sarana Nov 27 '17 at 19:57

2 Answers2

5

you can try this:

{% for key, address in user.address %}

In this way you have the key and the value

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
3

try this

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

and here documentation Iterating over Keys and Values

habibun
  • 1,552
  • 2
  • 14
  • 29