在 Twig 模板中,如何根据项目的属性值对数组中的项目进行分组?

问题描述 投票:0回答:1

在 PHP 中我会这样做:

$menu_groups = array();
foreach($items as $item){
    $menu_id = $item['properties.menu_id'];
    
    if(!array_key_exists($menu_id, $menu_groups)) $menu_groups[$menu_id] = array();
    
    $menu_groups[$menu_id][] = $item;
}

如何在 Twig 模板中完成类似的事情?

php symfony twig
1个回答
0
投票
you can do like this :  
{% set handledPeople = [] %}
{% for person in people if person not in handledPeople %}
    <div class="colour_container">
        {% for p in people if p.colour == person.colour and p not in handledPeople %}
            <p>{{ p.firstname }} {{ p.surname }} - {{ p.colour }}</p>
            {% set handledPeople = handledPeople|merge([p]) %}
        {% endfor %}
    </div>
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.