Remove duplicate and count them in row

╄→гoц情女王★ 提交于 2020-01-11 14:09:30

问题


I would like to delete duplicate entries and then count them to display them next to my entries in my php ROW

I've already tried this:

<?php                                       
foreach (array_unique($events) as $eventorga) {                                     
$eventorgan = $eventorga['organizer'];                                      
echo $eventorga['organizer'].'</br>';                                       
}                                       
?>

But an error: Array to string conversion is returned to me

<?php
foreach ($events as $eventorga) {
echo $eventorga['organisateur'].'</br>';
}
?>

Currently, my code returns this result:

Holyblood
Nessy
Pokégaia
Sorrow
JOHN
Holyblood

(From my MYSQL database)

I would like the return to be that:

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

回答1:


$eventResposne = array();

    array_walk($eventorga,function($responses,$index) use( &$eventResposne){
              if(isset($eventResposne[$responses['organisateur']])){
                       $eventResposne[$responses['organisateur']] = $eventResposne[$responses['organisateur']] + 1;
              }else{
                    $eventResposne[$responses['organisateur']] = 1;

              }       
    });

It will return an array like {'Holyblood':2,'Nessy':1,...}. Now use $eventResposne array to print the desired pattern.




回答2:


Try this.

$events =  [
            "Holyblood",
            "Nessy",
            "Pokégaia",
            "Sorrow",
            "JOHN",
            "Holyblood"
        ];
$eventCounts = [];
foreach ($events as $key => $eventorga) {
    if(!isset($eventCounts[$eventorga]))
        $eventCounts[$eventorga] = 0;
    $eventCounts[$eventorga]++   ;     

}
foreach ($eventCounts as $eventName => $eventCount) {
    echo $eventName . ' - ' . $eventCount . '<br>';
}


来源:https://stackoverflow.com/questions/54672012/remove-duplicate-and-count-them-in-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!