我正在使用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
我如何实现我的目标?
项目是包含SELECT *
修改
对不起,第二次只有在使用for(项目作为项目)时才会返回任何内容 当我使用items.stare时,我得到一个树枝错误:
Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78
答案 0 :(得分:1)
您应该在SQL中使用SELECT COUNT(*) FROM ... WHERE stare == 'active'
或其他东西来计算它们,并将其传递到您的树枝模板中。
或者,您可以在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
如果你真的想在树枝上做这一切,我不推荐,你可以这样做:
<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