同时使用三个变量用 Twig 指定数组中的值

Using three variables at same time to specify value in array with Twig

我有两个数组:teachers_number_array 包含教员 ID,另一个数组 'teachers' 包含每个老师的数据。

我不能做的是根据其id显示特定教师的姓名:

{% for teachers_number in teachers_number_array %}
    {% if teachers_number in teachers|keys %}
        {{ teachers.teachers_number.name }} 
    {% endif %}
{% endfor %}

你可以这样做。注意可以直接在Twig循环中获取数组的key(for id, teacher in teachers):

PHP 个变量:

$teachers_to_display = [2, 3];
$teachers =  [
    1 => 'Fabien',
    2 => 'COil',
    3 => 'Tokeeen',
    'do not display' => 'Nooooo',
];

树枝:

{% for id, teacher in teachers %}
    {% if id in teachers_to_display %}
        {{ teacher }}
    {% endif %}
{% endfor %}

将输出:

  • CO油
  • 托基恩

PS:如果您有多个属性,只需像以前一样使用 teacher.name

$teachers =  [
    1 => [
        'name' => 'Pot',
        'firstname' => 'Fabien',
...