Print Group Name above the list

Viewed 32

I have following array

[
  {
   id: 1,
   group_name: 'usa',
   state : 'San Francisco'  
 },
  {
   id: 2,
   group_name: 'usa',
   state : 'Texas'  
 },
  {
   id: 3,
   group_name: 'usa',
   state : 'North Carolina'  
 },  {
   id: 4,
   group_name: 'aus',
   state : 'Darwin'  
 },
  {
   id: 5,
   group_name: 'aus',
   state : 'Melbourne'  
 },
  {
   id: 6,
   group_name: 'usa',
   state : 'Perth'  
 }
]

I want to print as following:

Group Name: USA
State: San Francisco
State: Texas
State: North Carolina

Group Name: AUS
State: Darwin
State: Perth
State: Sydney

I tried following in twig but lacked in logic

             {% for place in places %}
                        <tr>
                            <td>{{ dump(place.getGroupName()) }}</td>
                        </tr>                        
                        <tr>
                                <td>{{ place.state}}</td>
                       </tr>
            {% endif %}

In the loop I want to put the country above the list of states. In the list of states the country must be top following by the states and same with the other countries as well.

1 Answers

Solution: "GroupBy" Array.

$groups = [
    [
        "id"=>1, 
        "group_name"=>"usa", 
        "state" => "San Franciso"
    ],
    [
        "id" => 2,
        "group_name" => "usa" ,
        "state"=> "Texas"
    ],
    [
        "id"=>3,
        "group_name"=>"usa",
        "state"=>"North Carolina"
    ],
    [
        "id" => 4,
        "group_name" => "aus",
        "state" => "Darwin"
    ],
    [
        "id" => 5,
        "group_name" => "aus",
        "state" => "Melbourne"
    ]
];

This is one of simple ways to GroupBy items in array, you should GroupBy "group_name" field. (https://www.delftstack.com/howto/php/php-group-arrays)

$grouped = array();

foreach ($groups as $element) {
    $grouped[$element['group_name']][] = $element;
}

You should get something like this:

[
  "usa" => [
    ["id" => 1, "state" => "Texas", "group_name" => "usa"],
    ["id" => 2, "state" => "North Carolina", "group_name" => "usa"],
    ["id" => 3, "state" => "Texas", "group_name" => "usa"],
  ],
  "aus" => [
    ["id" => 4, "state" => "Melbourne", "group_name" => "aus"],
    ["id" => 5, "state" => "Darwin", "group_name" => "aus"]
  ]
]

Suggestion: Before you send array to Twig, try to structure that array in this way:

$groups = [
   'usa' => [
      [ "id" => 1, "state" => "Texas" ],
      [ "id" => 2, "state" => "North Carolina" ],
      [ "id" => 3, "state" => "Texas" ],
   ],
   'aus" => [ 
      [ "id" => 4, "state" => "Darwin" ],
      [ "id" => 5, "state" => "Melbourne" ],
    ]

]

And after that creation, you only need to iterate over the array and display values without GroupingBy array in Twig.

Related