如何计算数组中的重复值

问题描述 投票:0回答:1
{% set valuesCars = ['bmw', 'mercedes', 'seat', 'porsche', 'seat', 'bmw', 'seat'] %}

{% set valuesIntegers = [27, 32, 36, 36, 27, 32, 32] %}

{% set counts = {} %}

{# Change valuesCars to valuesIntegers to output the integers #}
{% for value in valuesCars %}
    {% if counts[value] is not defined %}
        {% set counts = counts|merge({ (value): 1 }) %}
    {% else %}
        {% set counts = counts|merge({ (value): counts[value] + 1 }) %}
    {% endif %}
{% endfor %}

{% for key, count in counts %}
    {{ key }}: {{ count }}
{% endfor %}

对于 valuesCars 我得到正确的输出:
宝马:2
梅赛德斯:1
座位:3
保时捷:1

对于 valuesIntegers 我没有得到所需的输出。我明白了:
0:1
1:1
2:1
3:1
4:1
5:1
6:1

期望的输出应该是
27:2
32:3
36:2

我在这里缺少什么?

twig craftcms
1个回答
-1
投票

在集合计数结构中使用。

{% set valuesIntegers = [27, 32, 36, 36, 27, 32, 32] %}

{% set counts = {} %}

{% for value in valuesIntegers %}
    {% if counts[value] is not defined %}
        {% set counts = counts|merge({ (value): 1 }) %}
    {% else %}
        {% set counts = counts|merge({ (value): counts[value] + 1 }) %}
    {% endif %}
{% endfor %}

{% for key, count in counts %}
    {{ key }}: {{ count }}
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.