Twig forgets array-keys

2019-02-07 03:47发布

问题:

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.

回答1:

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



回答2:

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>


回答3:

It's not related on twig, it's a known gap in doctrine-mongodb using embeddedDocuments. Doctrine can't handle key-Values from embeddedDocuments, it will reorder the keys beginning from 0 and will so ignore the right key-values. Thank you anyway for your help :).