【问题标题】:Can we limit the if condition in for loop?我们可以限制 for 循环中的 if 条件吗?
【发布时间】:2021-06-13 06:26:12
【问题描述】:

我能否在一个 for 循环中只引入 12 个满足我想要的条件的内容?

{% for i, a in b %}
    
    {% if a.c[0].d == x %}

    {% elseif a.c[1].d == y %}

    {% endif %}

{% endfor %}

假设 b 中有 100 个项目。其中 60 个符合发布的 if 条件之一。但是,由于其中 40 个不满足,例如,7 个项目是由于 for 循环旋转 12 次而产生的。 5 个循环变为空。但是,我想要满足这些条件之一的总共 12 个项目。这可能吗?

注意:它不会给出正确的结果,如下所示

{% for i, a in b|slice(0, 12) %}
    
    {% if a.c[0].d == x %}

    {% elseif a.c[1].d == y %}

    {% endif %}

{% endfor %}

【问题讨论】:

  • 上面的代码有什么问题,你能分享更多细节
  • @HardikSatasiya 假设 b 中有 100 个项目。其中 60 个符合发布的 if 条件之一。但是,由于其中 40 个不满足,例如,7 个项目是由于 for 循环旋转 12 次而产生的。 5 个循环变为空。但是,我想要满足这些条件之一的总共 12 个项目。这可能吗?

标签: php laravel twig octobercms


【解决方案1】:

是的,可以这样做

例子

{% set items = [2,4,6,8,16,18,20,22,3,5,7,15,33,13, 25, 24, 28] %}
<h1> total records : {{items|length}} </h1>

{% set metWithConditionA  = [] %}
{% set metWithConditionB  = [] %}
{% set metWithConditionAB = [] %}

{% for item in items %}    
    {% if item % 2 == 0 %}
        {% set metWithConditionA = metWithConditionA|merge([item]) %}
        {% set metWithConditionAB = metWithConditionAB|merge([item]) %}        
    {% elseif item % 2 == 1 and item > 10%}
        {% set metWithConditionB = metWithConditionB|merge([item]) %}
        {% set metWithConditionAB = metWithConditionAB|merge([item]) %}        
    {% endif %}
{% endfor %}


<h1>metWithConditionA : {{metWithConditionA|length}}</h1>
{% for item in metWithConditionA %}    
    {{item}}
{% endfor %}

<hr/>
<h1>metWithConditionB : {{metWithConditionB|length}}</h1>
{% for item in metWithConditionB %}    
    {{item}}
{% endfor %}

<hr/>
<h1>metWithConditionAB : {{metWithConditionAB|length}}</h1>
{% for item in metWithConditionAB %}    
    {{item}}
{% endfor %}

<hr/>
<h1>12 items</h1>
{% for item in metWithConditionAB|slice(0, 12) %}    
    {{item}}
{% endfor %}

输出,现在您可以从metWithConditionAB 中取出 12 个项目并循环它们。

如有任何疑问,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    相关资源
    最近更新 更多