Search code examples
phpstringcountduplicatesshow

How to count and show duplicate in php string?


To create a ranking, I would like to count and then show duplicate entries in a string

<?php

$orgasql = "SELECT organisateur FROM events ";                                  
$orgareq = $bdd->prepare($orgasql);                                     
$orgareq->execute();                                        
while($eventrow = $orgareq->fetch(PDO::FETCH_ASSOC)) {                                      
$eventorgaas[] = $eventrow['organisateur'];                                     
}                                       
$eventimploded = implode(',',$eventorgaas);                                     
$eventimploded = implode(',',array_unique(explode(',', $eventimploded)));                                       
echo $eventimploded
?>

The current code returns this result :

Holyblood,Nessy,Pokégaia,Sorrow,JOHN

I would like the result to be this :

Holyblood - 2 ,Nessy - 1,Pokégaia - 1,Sorrow -1,JOHN -1

(There are two "Holyblood" occurrences in my database, array_unique delete duplica)


Solution

  • Just group by them by organisateur and count their occurences:

    <?php
    $orgasql = "SELECT organisateur, COUNT(*) as count FROM events GROUP BY organisateur";                                  
    $orgareq = $bdd->prepare($orgasql);                                     
    $orgareq->execute();                                        
    while($eventrow = $orgareq->fetch(PDO::FETCH_ASSOC)) {                                      
        $eventorgaas[] = $eventrow['organisateur'] . '-' . $eventrow['count'] ;                                     
    }                                       
    $eventimploded = implode(',',$eventorgaas);                                      
    echo $eventimploded
    ?>