0

I have an object where there are all my articles.

I'm currently looping my object to fill an array where I create an associative table for each article.

In my object I also have a Categories object and I would like to add the label of each category at the end of each associative array previously completed, but I don't know how to do that.. In the Categories object there may be multiple labels.

My code :

$articles = $this->entityManager->getRepository('SGBundle:Article')->findBy([], ['id'=>'desc']);

$arrayCollection = [];

foreach($articles as $article) {

    $arrayCollection[] = [
        'id' => $article->getId(),
        'date_publication' => $article->getDatePublication(),
        ...
    ];

    foreach($article->getCategories() as $categorie) {
        $arrayCollection[] = ['categorie' => $categorie->getLibelle()];
    }
}

enter image description here

On my screenshot, for each article there is an array with 36 values ​​and an array with 1 value and I would like this table to be in the table where there are 36 values. It's possible ?

2 Answers 2

1

First gather categories, then add'em to article item:

foreach($articles as $article) {
    $categories = [];
    foreach($article->getCategories() as $categorie) {
        $categories[] = $categorie->getLibelle();
    }

    $arrayCollection[] = [
        'id' => $article->getId(),
        'date_publication' => $article->getDatePublication(),
        ...
        // 
        'categorie' => $categories,
    ]; 
}
Sign up to request clarification or add additional context in comments.

Comments

0

If the article.categories field is marked as lazy, then it won't be hydrated by default and the $article->getCategories() will perform a new query on each loop round.

Instead of a simple findBy, you might want a custom DQL query in this case to optimize this and get the exact array you want in one single request.

Also note that your current query is fetching all articles of your database. While this is probably your purpose, keep in mind that this could get pretty heavy with the data growing. In most cases, this kind of query should be paginated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.