You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony Twig中如何统计城市关联对象的键数量?

问题解决:正确统计城市对应的对象数量

你的问题出在这段循环代码上:

{% for key in item.infoCity.announce|keys %}
    {{key|length }}
{% endfor %}

这段代码会遍历announce的所有键,每个数字类型的键(比如0、1、2)的长度都是1,所以会连续输出多个1,最终显示成11111这种形式,而不是总数量。

基础修复:统计单条目中的对象数量

正确的做法是直接使用Twig的length过滤器获取数组/对象的总元素数,不需要循环遍历键:

修改后的关键代码部分:

<button class=" m-2 p-2 pl-5 pr-5 bg-transparent border-2 border-red-500 text-red-500 text-lg rounded-lg hover:bg-gradient-to-b hover:from-red-600 hover:to-pink-500 hover:text-gray-100 focus:border-4 focus:border-red-300">
    {{ item.infoCity.city }}
    {{ item.infoCity.announce|length }}
    {% set newAnnounceCity = newAnnounceCity|merge([item.infoCity.city]) %}
</button>

进阶优化:统计城市的总对象数量

如果你的announceCity中同一个城市存在多个条目,上面的代码只会统计第一个条目中的announce数量,而非该城市的总数。这种情况下需要先按城市分组汇总:

{# 先遍历所有条目,按城市汇总announce总数 #}
{% set cityCounts = {} %}
{% for item in announceCity %}
    {% if item.infoCity is not null %}
        {% set city = item.infoCity.city %}
        {% set currentCount = cityCounts[city] is defined ? cityCounts[city] : 0 %}
        {% set cityCounts = cityCounts|merge({ (city): currentCount + item.infoCity.announce|length }) %}
    {% endif %}
{% endfor %}

{# 渲染每个城市的按钮 #}
{% for city, count in cityCounts %}
    {% set cityItem = announceCity|filter(item => item.infoCity.city == city)|first %}
    <span class=" font-semibold mr-2 text-left flex-auto">
        <a href="{{path('app_city_show',{slug: cityItem.infoCity.slug})}}">
            <button class=" m-2 p-2 pl-5 pr-5 bg-transparent border-2 border-red-500 text-red-500 text-lg rounded-lg hover:bg-gradient-to-b hover:from-red-600 hover:to-pink-500 hover:text-gray-100 focus:border-4 focus:border-red-300">
                {{ city }} {{ count }}
            </button>
        </a>
    </span>
{% endfor %}

这段代码会先汇总每个城市的所有announce数量,再渲染按钮,确保显示的是该城市的总对象数。

内容的提问来源于stack exchange,提问作者trouduc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:13