PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 11, 2022

[FIXED] How to merge duplicates

 May 11, 2022     doctrine-orm, symfony, twig     No comments   

Issue

I want to merge the same records to:

Audi A3 / S3 / RS3
   8V / 8Y
Audi A4 / S4 / RS4
   B8 / B9

etc.

But now it looks like that

Here is my repository code:

public function cars(): array
{
    $conn = $this->getEntityManager()->getConnection();

    $sql = 'select car.name as car, model.name as model from car join model on car.id = model.car_id';

    $stmt = $conn->prepare($sql);
    // returns an array of arrays (i.e. a raw data set)
    return $stmt->executeQuery()->fetchAllAssociative();
}

twig:

{% for car in cars %}
{{ car.car }}
{{ car.model }}
{% endfor %}

controller:

public function index(ModelRepository $modelRepository): Response
{
   $cars = $modelRepository->cars();

    return $this->render('index/index.html.twig', [
        'cars' => $cars,
    ]);
}

Can you give me some tips how to get it to work properly?


Solution

As mentioned in the comments, you need to restructure the resulting data array, that is, prepare the desired data structure and pass the template to twig.

Controller method:

public function index(ModelRepository $modelRepository): Response
{ 
    $cars = [];
    foreach ($modelRepository->cars() as $item) {
        $cars[$item['car']][] = $item;
    } 
    return $this->render('index/index.html.twig', [
        'cars' => $cars,
    ]);
}

Twig:

{% for key, car in cars %}
    {{ key }}
    {% for item in car %}
        {{ item.model }}
    {% endfor %}
{% endfor %}


Answered By - Harvey Dent
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing