Twig数组重复值统计异常:整数数组统计结果不符合预期
问题:Twig统计整数数组重复值结果异常
以下是用于统计数组重复值的Twig代码:
{% 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,能得到正确统计结果:
bmw: 2
mercedes: 1
seat: 3
porsche: 1
但切换为整数数组valuesIntegers时,输出结果不符合预期:
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
期望输出应为:
27: 2
32: 3
36: 2
原因分析
Twig中,当你尝试用整数作为关联数组的键时,会被自动当作索引数组的下标处理。比如用27作为键合并到空数组counts时,Twig会把它视为索引位置27,同时自动补全0到26的空索引,每个索引默认计数为1,这就导致输出完全偏离统计重复值的需求。
解决方案
将整数值转为字符串作为关联数组的键,让Twig将其当作普通关联键处理,避免触发索引数组的行为。修改后的代码如下:
{% set valuesIntegers = [27, 32, 36, 36, 27, 32, 32] %} {% set counts = {} %} {% for value in valuesIntegers %} {# 将整数转为字符串作为键 #} {% set key = value|string %} {% if counts[key] is not defined %} {% set counts = counts|merge({ (key): 1 }) %} {% else %} {% set counts = counts|merge({ (key): counts[key] + 1 }) %} {% endif %} {% endfor %} {% for key, count in counts %} {{ key }}: {{ count }} {% endfor %}
运行后即可得到期望的统计结果:
27: 2
32: 3
36: 2
内容的提问来源于stack exchange,提问作者Gilko
相关产品推荐
相关产品推荐

