如何从 Twig 的多维数组中获取值? [英] How to get values from a multidimensional array in Twig?
问题描述
我的数组 $strs[$key][$id] 的 var_dump 给出了以下结果:
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"
}
}
在我看来,我想从所有 $key 中获取具有相同 $id 的所有字符串.像这样:
1-
ouvrir 1
枪骑兵2
2-
费希尔2
枪骑兵 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
等
我在我的树枝视图中试过这个:
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 %}
我收到此错误:
键为0, 1"的数组的键键"不存在于...
我在这里做错了什么?我怎样才能得到我正在寻找的结果?
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;
}
}
结果将是一个数组,其键将是 ID,属于同一 ID 的字符串的值数组.
The result will be an array whose keys will be the IDs, the values arrays of strings that belong to the same ID.
显示:
{% for id, stringsById in results %}
{{ id }}- <br />
{% for string in stringsById %}
{{ string }} <br />
{% endfor %}
{% endfor %}
这篇关于如何从 Twig 的多维数组中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!