在树枝中重组数组

Reorganize array in twig

我想反转我的数组,以便类别在前,以便我以后可以更好地管理我的 foreach。 我设法实现了,但是合并删除了相同的键。而且我不应该将值添加为数组中的另一项。

默认数组:

array:10 [
0 => array:2 [
    "type" => "type1"
    "object" => {
        name: "Sample name 1"
        category: "Cat1"
    }
]
1 => array:2 [
    "type" => "type1"
    "object" => {
        name: "Sample name 2"
        category: "Cat2"
    }
]
2 => array:2 [
    "type" => "type1"
    "object" => {
        name: "Sample name 3"
        category: "Cat1"
    }
]
3 => array:2 [
    "type" => "type1"
    "object" => {
        name: "Sample name 4"
        category: "Cat2"
    }
]

合并后:( 删除了两条记录:()

array:2 [
  "Cat1" => array:2 [
    "type" => "type1"
    "object" => ...
  ]
  "Cat2" => array:2 [
    "type" => "type1"
    "object" => ...
  ]
]

他想达到什么目的?

array:2 [
    "Cat1" => array:2 [
        0 => array:2 [
            "type" => "type1"
            "object" => {
                name: "Sample name 1"
                category: "Cat1"
            }
        ]
        1 => array:2 [
            "type" => "type1"
            "object" => {
                name: "Sample name 3"
                category: "Cat1"
            }
        ]
    ]
    "Cat2" => array:2 [
        0 => array:2 [
            "type" => "type1"
            "object" => {
                name: "Sample name 2"
                category: "Cat2"
            }
        ]
        1 => array:2 [
            "type" => "type1"
            "object" => {
                name: "Sample name 4"
                category: "Cat2"
            }
        ]
    ]
]

代码:

{% set organised_cats = {} %}

{% for element in sourceElements %}
    {% set organised_cats = organised_cats|merge({
    (element.object.category) : element
    }) %}
{% endfor %} 

首先,仅供参考,这不是您应该在模板中执行的操作,因为代码非常混乱。无论如何,这是 merge/group 在 twig:

中的数组
{% set output = [] %}
{% for item in items %}
    {% if not attribute(output, item.object.category) is defined %}
        {% set output = output|merge({ (item.object.category) : {}, }) %}
    {% endif %}

    {% set output = output|merge({(item.object.category) : output[item.object.category] | merge([ item, ]) }) %}
{% endfor %}

{% for category, items in output %}
    {{ category }}:
        {% for item in items %}
            {{ item.object.name }}
        {% endfor %}
{% endfor %}

demo

issues with merge in twig