Wednesday, May 11, 2022

[FIXED] How to merge duplicates

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)

No comments:

Post a Comment

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