Duplicate results in foreach data in the data table with Php in symfony

I have a list of user, and a list of action he has performed. When I try to display the user is registered and the history data from both tables, I get duplicate results. I use my HistoryManagerController to get the information about the actions and the user who performed them, The code below works except I get duplicate results where the first result in the table matches 100%, the second result does not match, then continues with the same duplicate value for each user. I know these are basic things that people need to do, so if anyone can point me in the right direction of what I need to learn to make this happen, it will help me throughout my project.

Thank you!

HistoryController

<?php

namespace App\Controller;

use App\Entity\ActionHistorique;
use App\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Services\HistoriqueLogs;
use Doctrine\Persistence\ManagerRegistry;



class GestionHistoriqueController extends AbstractController
{
    /**
     * @var HistoriqueLogs
     */
    private $logHistorique;
    /**
     * @var ManagerRegistry
     */
    private $doctrine;

    public function __construct(
        HistoriqueLogs $logHistorique,
        ManagerRegistry $doctrine
    ) {
        $this->logHistorique = $logHistorique;
        $this->doctrine = $doctrine;
    }
    /**
     * @Route("/gestion/historique", name="app_gestion_historique")
     */
    public function dashboardAdmin(RequestStack $requestStack): Response
    {
    $params = $requestStack->getSession();
    $user = $this->getUser();
    $projet =  $params->get('projet');
    $modules = $params->get('modules');
    $fonctionnalites = $params->get('fonctionnalites');
    $adresseWeb = $this->getParameter('adresse_web');

    $actionHistoriques = $this->doctrine->getRepository(ActionHistorique::class)->findBy(['projetId' => $projet->getId()]);

     $projetNom = $projet->getProjet();

    $dataJson = array();

foreach ($actionHistoriques as  $actionHistorique) {

    $listUsers = $this->doctrine->getRepository(Users::class)->findAll();

 /* getter pour r?�cuperer les nom et prenom des id associ?� aux utilisateurs dans le tableau.
 Et ensuite faire le reste dans le deuxi??me foreach et call le tableau pour le remplir */

    foreach ($listUsers as $user) {
        
    $nomUser = $user->getNom();
    $prenomUser = $user->getPrenom();

        // Injection des donn?�es dans le tableau 
        $mesDonnes = array(

            "nom"=> $nomUser,
            "prenom"=> $prenomUser,
            "projet"=> $projetNom,
            "date"=> $actionHistorique->getDate()->format('d/m/Y'),
            "actionEffectu?�e"=> $actionHistorique->getAction(),
            "CodeST/TI/PT/LT/BP/BA"=> $actionHistorique->getCode(),
            "nomCode"=> $actionHistorique->getNom(),
        );
        
        $dataJson[] = $mesDonnes;          
    }
}
            return $this->render('Historique/gestionHistorique.html.twig', [
                'user' => $user,
                'projet' => $projet,
                'modules' => $modules,
                'fonctionnalites'=> $fonctionnalites,
                'adresseWeb'=> $adresseWeb,
                'actionHistorique'=> json_encode($dataJson),
            ]);
        }
    }

GestionHistory

 {% extends 'base.html.twig' %}

{% block stylesheets %}
    {{ parent() }}
    {{encore_entry_link_tags('tabulator')}}

{% endblock %}
    {% block sudalysBody %}
    <section>
      <div id="singleTab" class="box box-info">
        <div class="box-header with-border">
    <h2 class="box-title">Historique Easy Exploit</h2>
        </div>
        <div id="infos">
<div>
  <select id="filter-field">
    <option value="nom">Nom</option>
    <option value="pr?�nom">Pr?�nom</option>
    <option value="projet">Projet</option>
    <option value="actionEffectu?�e">Action effectu?�e</option>
    <option value="CodeST/TI/PT/LT/BP/BA">Code de l'objet</option>
    <option value="nomCode">Nom de l'objet</option>
  </select>

  <select id="filter-type">
    <option id="filter-type" value="like"></option>
  </select>

  <input id="filter-value" type="text" placeholder="Rechercher">

  <button id="filter-clear">R?�intialiser</button>
</div>
          <div id="monTable"></div>
        </div>
      </div>
    </section>
        
    {% endblock %}

{% block javascripts %}
    {{ parent() }}

<script>
 var gestionHistorique = '{{actionHistorique | e('js') | raw}}';
gestionHistorique = JSON.parse(gestionHistorique);

// gestionHistorique.forEach( e => {
//   console.log(e);
  
// });
  $(document).ready(function() {

//custom max min header filter
var minMaxFilterEditor = function(cell, onRendered, success, cancel, editorParams){

    var end;

    var container = document.createElement("span");

    //create and style inputs
    var start = document.createElement("input");
    start.setAttribute("type", "date");
    start.setAttribute("placeholder", "Min");
    start.style.padding = "6px";
    start.style.width = "50%";
    start.style.boxSizing = "border-box";

    start.value = cell.getValue();

    function buildValues(){
        success({
            start:start.value,
            end:end.value,
        });
    }

    function keypress(e){
        if(e.keyCode == 13){
            buildValues();
        }

        if(e.keyCode == 27){
            cancel();
        }
    }

    end = start.cloneNode();
    end.setAttribute("placeholder", "Max");

    start.addEventListener("change", buildValues);
    start.addEventListener("blur", buildValues);
    start.addEventListener("keydown", keypress);

    end.addEventListener("change", buildValues);
    end.addEventListener("blur", buildValues);
    end.addEventListener("keydown", keypress);


    container.appendChild(start);
    container.appendChild(end);

    return container;
 }

//custom max min filter function

function 
minMaxFilterFunction(headerValue,rowValue,rowData,filterParams) {
//headerValue - the value of the header filter element
//rowValue - the value of the column in this row
//rowData - the data for the row being filtered
//filterParams - params object passed to the headerFilterFuncParams property
//convert strings into dates

    if (headerValue.start != "") {
        headerValue.start = new Date(headerValue.start);
    }

    if (headerValue.end != "") {
        headerValue.end = new Date(headerValue.end);
    }

    if(rowValue){
        const [day, month, year] = rowValue.split('/');
        const result = [year, month, day].join('-');
        var rowValue1 = new Date(result);

        if(headerValue.start != ""){
            if(headerValue.end != ""){
                if(rowValue1 >= headerValue.start && rowValue1 <= headerValue.end){
                        return true;
                }else{
                    return false;
                }
            }else{
                if(rowValue1 >= headerValue.start){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            if(headerValue.end != ""){
                if(rowValue1 >= headerValue.end){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }
    return true; 
//must return a boolean, true if it passes the filter.
}
//Define variables for input elements
var fieldEl = document.getElementById("filter-field");
var typeEl = document.getElementById("filter-type");
var valueEl = document.getElementById("filter-value");

//Trigger setFilter function with correct parameters
function updateFilter(){
  var filterVal = fieldEl.options[fieldEl.selectedIndex].value;
  var typeVal = typeEl.options[typeEl.selectedIndex].value;

  var filter = filterVal == "function" ? customFilter : filterVal;

  if(filterVal == "function" ){
    typeEl.disabled = true;
    valueEl.disabled = true;
  }else{
    typeEl.disabled = false;
    valueEl.disabled = false;
  }

  if(filterVal){
    table.setFilter(filter,typeVal, valueEl.value);
  }
}

//Update filters on value change
document.getElementById("filter-field").addEventListener("change", updateFilter);
document.getElementById("filter-type").addEventListener("change", updateFilter);
document.getElementById("filter-value").addEventListener("keyup", updateFilter);

//Clear filters on "Clear Filters" button click
document.getElementById("filter-clear").addEventListener("click", function(){
  valueEl.value = "";

  table.clearFilter();
});
var table = new Tabulator("#monTable", {
     
          data: gestionHistorique,
          layout: "fitColumns",
          pagination: "local",
          paginationSize: 20,
          paginationSizeSelector: [20, 40, 60, 100],
          paginationCounter: "rows",
          paginationCounter: "rows",
    columns:[
        {title:"Nom", field:"nom",hozAlign:"center"},
        {title:"Pr?�nom", field:"prenom",hozAlign:"center"},
        {title:"Projet", field:"projet",hozAlign:"center"},
        {title:"Date", field:"date", sorter:"datetime",hozAlign:"center",formatter:"datetime", formatterParams:{
                inputFormat:"dd/MM/yyyy",
                outputFormat:"dd/MM/yyyy",
                invalidPlaceholder:"(invalid date)",
            },  headerFilter:minMaxFilterEditor, headerFilterFunc:minMaxFilterFunction, headerFilterLiveFilter:false},
         {title:"Action effectu?�e",field:"actionEffectu?�e",hozAlign:"center"},
        {title:"Code Objet", field:"CodeST/TI/PT/LT/BP/BA",hozAlign:"center"},
        {title:"Nom Objet", field:"nomCode",hozAlign:"center"},
    ],
    });
});

</script>
  
{% endblock %}

Answer

Solution:

1 Try moving the code:

$listUsers = $this->doctrine->getRepository(Users::class)->findAll();

before the foreach:

...
$dataJson = array();

$listUsers = $this->doctrine->getRepository(Users::class)->findAll();

foreach ($actionHistoriques as  $actionHistorique) {

/* getter pour r?�cuperer les nom et prenom des id associ?� aux utilisateurs dans le tableau.
   Et ensuite faire le reste dans le deuxi??me foreach et call le tableau pour le remplir */
...

I had encountered a similar problem when iterating over entityRepository find() call.

And if it doesn't solve your problem at least you will have better performances.

EDIT:

2 It seems that in your code you don't check if the action you are iterating is being done by the user in the inner foreach. So for each action and each user you retrieved from the database you add an entry in the $mesDonnes array.

I suppose that the 2 tables are linked by a foreign key or other reference and the code should be more something like:

foreach ($actionHistoriques as $actionHistorique) {
   $user = $actionHistorique->getUser();
   $nomUser = $user->getNom();
   $prenomUser = $user->getPrenom();
   $mesDonnes = ....
           
   $dataJson[] = $mesDonnes;
}

//or
foreach ($actionHistoriques as $actionHistorique) {
   foreach ($listUsers as $user) {
       // madeThisAction() is a method that you should code specifically for your project
       if ($user->madeThisAction($actionHistorique)) {       
           $nomUser = $user->getNom();
           $prenomUser = $user->getPrenom();
           $mesDonnes = ....
           
           $dataJson[] = $mesDonnes;
       }
   }
}

Source