如何从 Twig 中的多维数组中获取值? [英] How to get values from a multidimensional array in Twig?
问题描述
A var_dump for my array $strs[$key][$id] gives the following result:
array(2) {
[0]=> array(4) {
[8259]=> string(8260) "ouvrir 1"
[8260]=> string(8261) "fichier 2"
[8261]=> string(8262) "quitter 1"
[8262]=> string(8263) "lire 2"
}
[1]=> array(4) {
[8259]=> string(8260) "lancer 2"
[8260]=> string(8261) "dossier 1"
[8261]=> string(8262) "exit 1"
[8262]=> string(8263) "lire 2"
}
}
In my view, I'm tying to get all the strings with the same $id from all the $key. Something like this:
1-
ouvrir 1
lancer 2
2-
fichier 2
lancer 2
etc
I've tried this in my twig view:
{% for key,val in strs['key']['id'] %}
{% if strs['key']['id'] is defined %}
{{ key }} - <br/>
{{ val }}
{% endif %}
{% endfor %}
I got this error:
Key "key" for array with keys "0, 1" does not exist in...
What Am I doing wrong here? And how can I get the result I'm looking for?
Don't put this logic in your views. Use your views only to display stuff.
Do it in your controller instead and pass the result to your view:
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
$result[$key][] = $value;
}
}
The result will be an array whose keys will be the IDs, the values arrays of strings that belong to the same ID.
To display it:
{% for id, stringsById in results %}
{{ id }}- <br />
{% for string in stringsById %}
{{ string }} <br />
{% endfor %}
{% endfor %}
这篇关于如何从 Twig 中的多维数组中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!