对每个数组值求和
我有一个数组,想要对每个索引的值求和。我该怎么做?
sortiment: shoe1,AD12,Nike,0,1,2,0,3,2,0,0,1
所以我将行排序分成
{% set sortimentArray = key.sortiment|split(',') | slice(3)%}
现在我只将数字保存在排序数组中。我怎样才能对它们求和?
{% for key in sortimentArray %}
{# code to sum the values and save them in a variable #}
{% set allIndexValues = sortimentArray[0] + 1 %}
{% endfor%}
{{ allIndexValues }}
这是行不通的,我刚刚编出来的,有人能帮忙解释一下这个理论吗?在这种情况下,应该输出值 9
i have an array and want to sum their value for each index. how can i do that ?
sortiment: shoe1,AD12,Nike,0,1,2,0,3,2,0,0,1
so i split the row sortiment into
{% set sortimentArray = key.sortiment|split(',') | slice(3)%}
now i only have the numbers saved in sortimentArray. how can i sum them ?
{% for key in sortimentArray %}
{# code to sum the values and save them in a variable #}
{% set allIndexValues = sortimentArray[0] + 1 %}
{% endfor%}
{{ allIndexValues }}
this doesnt work and i jsut made it up, can anyone help with the theory ? in this case a value of 9 should come out
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看夏季化上方的 Twig sum 行。您可以使用
reduce
过滤器轻松求和您的值Have a look at Twig sum row above the summerisation. You can use the
reduce
filter to easily sum your values有人给了我这个解决方案,但删除了他的答案。多亏了他,这才成功。
Some one gave me this solution but delete his answer. Thanks to him this worked.
您必须在 for 循环外部声明
allIndexValues
变量,否则该变量仅在 for 循环内部具有作用域,并且在循环外部未定义。当您在
twig
中启用调试模式并尝试在循环外访问它时,这实际上会引发变量“allIndexValues”不存在
的错误。twig 中正确的 for 循环定义为
{% for value in array %}
因此不确定为什么要引用sortimentArray[0]
因为您可以获得正确的值在变量key
demo
You have to declare your
allIndexValues
variable outside the for-loop, otherwise this variable only has a scope inside the for-loop and is undefined outside the loop.This would actually throw an error that
variable "allIndexValues" does not exist
when you enable the debug mode intwig
and try to access it outside the loop.The proper for-loop in twig is defined as
{% for value in array %}
so not sure why you are referencingsortimentArray[0]
as you can the get correct value in the variablekey
demo