douyuanliao8815 2017-03-29 17:45
浏览 46
已采纳

以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
  • 写回答

1条回答 默认 最新

  • duankeng2026 2017-03-29 17:52
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度