我正在将 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 *
编辑
抱歉,第二个仅在使用 for(items as item) 时才返回任何内容 当我使用 items.stare 时,出现 Twig 错误:
Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78
最佳答案
您可能应该用 SQL 来计算它们,使用 SELECT COUNT(*) FROM ... WHERE stare == 'active'
或其他内容,然后将其传递到您的 twig 模板中。
或者,您可以在 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
关于php - 用 TWIG 进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100600/