问题
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