【问题标题】:How can I loop from an entry in the array to the end? twig/php如何从数组中的条目循环到末尾?树枝/php
【发布时间】:2018-10-23 12:51:53
【问题描述】:

我已要求对如下所示的数组进行循环:

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~   ~
)

我需要从数组的条目 46 循环到末尾,我尝试做一些事情但根本没有工作,而且我必须只在 Twig 中做这件事,所以我有点失落。我可以使用 twig 的 lastfunction 获取数组的最后一个条目。但找不到获取最后一个条目的东西。

【问题讨论】:

标签: php loops twig


【解决方案1】:

在 twig 中,您可以使用 for 循环来完成此操作:

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

查看示例输出here

另外(感谢splash58's comment),您可以通过slice operator 访问。来自文档:

{% 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" #}

所以你可以做到这一点,如下所示:

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

查看此here 的示例输出。

【讨论】:

  • 我猜 OP 在 twig 中需要它,而不是 PHP。
  • 这就是重点,我可以在 php 上做到这一点,但我不知道如何在 Twig 中重现它。我已经查看了 twig 的文档,但是.. twig.symfony.com/doc/2.x/tags/for.html
  • @wiitohzjeh 我已经更新了我的帖子(我很抱歉,当我浏览它时将它读为 PHP)。
  • 谢谢,我终于明白了:
【解决方案2】:

您可以在for 中使用loop 变量

{% 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多