以TWIG计数
问题描述:
I'm using SILEX with twig and I'm trying to achieve an count for an array from db with a specific value Here is the piece of code to be more specific:
<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
How can I achieve what I want?
items is an array with information from a SELECT *
EDIT
I'm sorry , the second returns nothing only when using an for(items as item) When I use items.stare I get a twig error:
Key "stare" for array with keys "0, 1, 2, 3, 4" does not exist in "index.twig" at line 78
答
You should probably count them in SQL, with a SELECT COUNT(*) FROM ... WHERE stare == 'active'
or something, and pass that into your twig template.
Or, you could filter it in PHP and pass the filtered array to your template:
$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
If you really want to do it all in twig, which I don't recommend, you could do:
<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