Tri CreatedAt d'un array_merge

Par just_real, il y a 4 ans


Bonjour,

Je suis sous Symfony 5, ma question : Est-il possible de trier les données d'un array_merge (de plusieurs entités) -> par createdAt ?

$VariableUn = $this->getDoctrine() ->getRepository(Un::class) ->findAll(); $VariableDeux = $this->getDoctrine() ->getRepository(Deux::class) ->findAll(); $VariableTrois = $this->getDoctrine() ->getRepository(Trois::class) ->findAll(); $ListeVariable = array_merge( $VariableUn, $VariableDeux, $VariableTrois );

Ce que je veux --> Trier toutes les données de $ListeVariable par date de création dans ma vue (tableau html)

Ce que j'obtiens --> Je peux trier chaque variable indépendamment les unes des autres via

$VariableUn = $this->getDoctrine() ->getRepository(Un::class) ->createQueryBuilder('a') ->orderBy('a.createdAt', 'DESC') ->getQuery() ->getResult() ; etc etc

Mais forcement ça ne donne pas le résultat attendu sur ma vue une fois mergé avec les autres.

merci

1 réponse

Alex-trem, il y a 4 ans

Tu peux faire quelque chose comme ça par exemple :

$array = [ 0 => [ "name" => "a", "date" => "2020-12-05" ], 1 => [ "name" => "b", "date" => "2020-12-02" ], 2 => [ "name" => "c", "date" => "2020-12-01" ], 3 => [ "name" => "d", "date" => "2020-12-04" ], 4 => [ "name" => "e", "date" => "2020-12-03" ], 5 => [ "name" => "f", "date" => "2020-12-06" ], ]; usort( $array, function ($a, $b) { $dateA = new DateTime($a['date']); $dateB = new DateTime($b['date']); return $dateA->getTimeStamp() - $dateB->getTimeStamp(); } );