'sum each array value
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
Solution 1:[1]
Have a look at Twig sum row above the summerisation. You can use the reduce filter to easily sum your values
Solution 2:[2]
Some one gave me this solution but delete his answer. Thanks to him this worked.
{% set total = 0 %}
{% for value in key.sortiment|split(',')|slice(3) %}
{% set total = total + value %}
{% endfor %}
{{ total }}
Solution 3:[3]
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 in twig 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 referencing sortimentArray[0] as you can the get correct value in the variable key
{% for item in items %}
{% set total = 0 %}
{% for value in item.sortiment|split(',')|slice(3) %}
{% set total = total + value %}
{% endfor %}
Total: {{ total }}
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeroen |
| Solution 2 | Zy T othman |
| Solution 3 | DarkBee |
