php - 用 TWIG 进行计数

标签 php twig silex

我正在将 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/

相关文章:

java - 在Android中显示Mysql数据

php - Laravel 5 - 不断重复使用语句

php - 如何整理多个 if 条件以提高可读性?

php - MYSQL在PHP中仅询问第一排名时不返回结果

php - 与 TWIG 的关系

php - 自定义服务提供商的silex文件结构

php - EzPublish 根据页面类型使用不同的模板

twig - Twig 中的动态变量,例如?

symfony - 尝试在 Silex 2 中的类 "share"上调用方法 "Silex\Application"

PHP 表单 - 上传文件,想要使用 Silex 但不想使用 FormBuilder