Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig forgets array-keys

I have a weird problem with twig in Symfony2. I am using the following array:

[days] => Array
    (
        [1] => Array
            (
                [money] => 9
            )

        [2] => Array
            (
                [money] => 21
            )

        [3] => Array
            (
                [money] => 38
            )

        [4] => Array
            (
                [money] => 6
            )

        [18] => Array
            (
                [money] => 6
            )

        [19] => Array
            (
                [money] => 3
            )

        [31] => Array
            (
                [money] => 11
            )

    )

to test this I used the following code

{% for key in days %}
  {{ key }}<br>
{% endfor %}

but the output shows the following

0
1
2
3
4
5
6

but it should look like this

1
2
3
4
18
19
31

Looks like twig creates a new array with new indexes. Is there a way to get the right index from array?

With var_dump($days) in php I can see the right index, so the "problem" is related to twig.

like image 741
mrohnstock Avatar asked Jun 01 '11 07:06

mrohnstock


People also ask

What is array keys used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How do you find the key and value of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.


2 Answers

also you can try this :

{% for key,value in users %}
    {{ key }}
{% endfor %}

or maybe look into the "loop" object defined in the for loop

http://twig.sensiolabs.org/doc/tags/for.html

like image 86
Jack3D Avatar answered Oct 22 '22 23:10

Jack3D


Maybe this

http://www.twig-project.org/doc/templates.html

By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:

<h1>Members</h1>
<ul>
  {% for key in users|keys %}
    <li>{{ key }}</li>
  {% endfor %}
</ul>
like image 8
azat Avatar answered Oct 22 '22 21:10

azat