如何从Twig中的多维数组中获取值?

时间:2022-04-01 12:41:21

A var_dump for my array $strs[$key][$id] gives the following result:

我的数组$ strs [$ key] [$ id]的var_dump给出以下结果:

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

在我看来,我想要从所有$ key获得所有带有相同$ id的字符串。像这样: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?

我得到了这个错误:键“0,1”的数组的键“键”不存在于......我在这里做错了什么?我怎样才能得到我正在寻找的结果?

1 个解决方案

#1


10  

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.

结果将是一个数组,其键将是ID,属于相同ID的字符串数组的值。

To display it:

要显示它:

{% for id, stringsById in results %}
  {{ id }}- <br />
  {% for string in stringsById %}
    {{ string }} <br />
  {% endfor %}
{% endfor %}

#1


10  

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.

结果将是一个数组,其键将是ID,属于相同ID的字符串数组的值。

To display it:

要显示它:

{% for id, stringsById in results %}
  {{ id }}- <br />
  {% for string in stringsById %}
    {{ string }} <br />
  {% endfor %}
{% endfor %}