'Loop through multidimensional Array with a variable as a property for another variable
I need to loop through an multidimensional array in twig.
//EDIT: I still haven't found the solution, i tried the suggestion with attribute, but it did not work.. here you can see the whole code plus error message, maybe someone can help me. I really try to unterstand the problem, but every attempt at a solution fails :/
First i have the array category with different strings.
The strings are user-defined, so they are different depending on the user. E.g.: Car, Food, Sport
The second array array is multidimensional an looks like this:
array(12) {
["01"]=>
array(3) {
["Food"]=>float(861)
["Car"]=>float(300)
["Sport"]=>float(80)
}
["02"]=>
array(3) {
["Food"]=>float(12)
["Car"]=>float(199)
["Sport"]=>int(0)
}
["03"]=>
array(3) {
["Food"]=>int(0)
["Car"]=>int(0)
["Sport"]=>float(80)
}
… 9 more
My Twig Code looks like this
{% for category in categorys %}
<tr>
<th>{{category}}</th>
{% for line in array %}
<td> {{ attribute(line, category) }} </td
{% endfor %}
</tr>
{% endfor %}
The final table should look like this:
| Food | 861 | 300 | 80 |
| Car | 12 | 199 |0 |
| Sport | 0 | 0 | 80 |
When i use the attribute functions the errormessage is: Illegal offset type in isset or empty
**TypeError in C:\xampp\htdocs\MMM2\vendor\twig\twig\src\Extension\CoreExtension.php (line 1437)
--> if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object))) || ($object instanceof ArrayAccess && isset($object[$arrayItem]))**
How can i use the variable category in this context? Maybe someone can help me, I don't know how to continue.. Thanks in advance!
Solution 1:[1]
Okay guys, thanks to everyone, especially to Bjorn for the help. I finally found my problem because of a zoomtalk with a friend of mine who is more experienced than me in php.
My problem was the category-array.. This array saved not only texts but entire objects.. so i must add .name to category, that i get the Strings "Food, Car, Sport"...
The answer looks like this
<table>
{% for category in categories %}
<tr>
<th>{{ category }}</th>
{% for line in values %}
<td>{{ attribute(line, category.name) }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Thanks again for your effort!
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 | LittleEast |
