Issue
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
I'm not totally sure what you're after and I'm not totally sure what your data structure looks like. But if your data looks like this:
$this->render('foo.html', [
'categories' => [ 'Food', 'Car', 'Sport' ],
'values' => [
[ 'Food' => 861, 'Car' => 300, 'Sport' => 80 ],
[ 'Food' => 12, 'Car' => 199, 'Sport' => 0 ]
]
]);
Something like this should work:
<table>
{% for category in categories %}
<tr>
<th>{{ category }}</th>
{% for line in values %}
<td>{{ attribute(line, category) }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
It should render this:
<table>
<tr>
<th>Food</th>
<td>861</td>
<td>12</td>
</tr>
...
</table>
Answered By - Bjorn
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.