I want to invert my array so that the categories are first so that I can better manage my foreach later. I managed to achieve it, but merge has removed the same keys. And I should not add value as another item in the array.
Default Array:
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" } ]
After Merge: ( two records have been deleted :()
array:2 [ "Cat1" => array:2 [ "type" => "type1" "object" => ... ] "Cat2" => array:2 [ "type" => "type1" "object" => ... ] ]
What is he trying to achieve?
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" } ] ] ]
Code:
{% set organised_cats = {} %} {% for element in sourceElements %} {% set organised_cats = organised_cats|merge({ (element.object.category) : element }) %} {% endfor %}
Advertisement
Answer
First a FYI though, this is not something you should be doing in the template, cause the code is pretty messy. Anyway here is how you merge/group arrays in 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 %}