在 TWIG 中计数

Counting in TWIG

我正在将 SILEX 与 twig 一起使用,并且我正在尝试从具有特定值的 db 中对数组进行计数 这是一段更具体的代码:

 <p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
 <p>There are  {{ items.stare=='activ'|length }} requests not answered.</p> // returns nothing

我怎样才能达到我想要的?

items 是一个包含来自 SELECT *

的信息的数组

编辑

对不起,第二个 returns 只有在使用 for(items as item) 时才没有 当我使用 items.stare 时出现树枝错误:

Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78

您可能应该用 SELECT COUNT(*) FROM ... WHERE stare == 'active' 或其他方式将它们数在 SQL 中,然后将其传递到您的树枝模板中。

或者,您可以在 PHP 中过滤它并将过滤后的数组传递给您的模板:

$activ_items = array_filter($items, function($item) {
    return $item['stare'] == 'active';
});

<p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
<p>There are  {{ activ_items|length }} requests not answered.</p> // returns nothing   

如果你真的想在 twig 中全部完成,我不推荐,你可以这样做:

<p>There are in total {{ items|length }}</p> // returns the GOOD amount of total rows in db
{% set count = 0 %}
{% for item in items %}
    {% if item.stare == "activ" %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}
<p>There are  {{ count }} requests not answered.</p> // returns nothing