简体   繁体   中英

How can I loop from an entry in the array to the end? twig/php

I've asked to do a loop into an array who looks like this:

Array
(
    [0] => 215950741
    [1] => 3900
    [2] => 10527160
    [3] => 2873
...
    [44] => N~~~~
    [45] => N~~~~
    [46] => historico_estados
    [47] => 18/10/2018 16:03:09~10~Solicitada~ARANJUEZ~0~2873~   ~
    [48] => 18/10/2018 16:06:42~13~Aceptada~ARANJUEZ~0~2873~   ~
    [49] => 18/10/2018 18:15:49~3~Tránsito~SANTANDER~0~3900~   ~
    [50] => 18/10/2018 22:28:49~3~Tránsito~PLATVITORIA~0~9001~   ~
    [51] => 19/10/2018 04:19:33~3~Tránsito~PLATMADRID~0~9028~   ~
    [52] => 19/10/2018 08:15:53~2~Reparto~ARANJUEZ~0~2873~   ~
    [53] => 19/10/2018 09:37:00~1~Entregado~RECEPTOR~0~2873~   ~
)

I need to loop from the entry 46 of the array to the end, I've tried to do something but isn't working at all, and the plus of this I had to do it solely in Twig, so I am kinda lost. I can get the last entry of the array using the last function of twig.. but can't find something to get the last entries.

In twig, you could accomplish this with a for loop:

{% for i in 44..array|length-1 %}
    {{ array[i] }}
{% endfor %}

See an example output here .

Additionally (Thanks to splash58's comment ), you can access via the slice operator . From the docs:

 {% for i in [1, 2, 3, 4, 5][start:length] %} {# ... #} {% endfor %} {{ '12345'[1:2] }} {# will display "23" #} {# you can omit the first argument -- which is the same as 0 #} {{ '12345'[:2] }} {# will display "12" #} {# you can omit the last argument -- which will select everything till the end #} {{ '12345'[2:] }} {# will display "345" #} 

So you can accomplish this, like below:

{% for item in array[44:] %}
   {{ item }}
{% endfor %}

See an example output of this here .

You can use loop variable inside for

{% for el in elems %}
    {% if loop.index0 > 45 %}
        {# do some stuff #}
    {% endif %}
{% endfor %}

https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM