1

I ran an election that has a variable number of winners for each category. (One category can have 3 winners, another 1 winner, another 2 winners, etc.)

Currently I am displaying the results like this:

foreach($newarray as $key => $value){

                echo $key . $value . “<br>”;
}

This returns

    Barack Obama 100
    Mitt Romney 100
    John Smith 94
    Jane Smith 85

What I need to do is have it echo out something if two of the values are the same based on that predetermined number. So, if the predetermined number was one, it would show this:

    Barack Obama 100 tie
    Mitt Romney 100 tie
    John Smith 94
    Jane Smith 85

If the predetermined number was two, it would show this since the second and third values aren’t the same:

    Barack Obama 100 winner
    Mitt Romney 100 winner
    John Smith 94
    Jane Smith 85

Thank you for your time.

4

1 回答 1

0
$max = max($array);
$tie = count(array_keys($array,$max)) > $predeterminedNumber;
foreach($newarray as $key => $value){
     echo $key . $value . ($value==$max ? ($tie ? ' tie' :' winner') : ''). '<br>';
}

尽管如果您需要 3 个获胜者不一定具有相同的分数,它会变得有点复杂:

$predefinedNumber = whatever;
arsort($array);

//first $predefinedNumber are either winners or tied.
$winners = array_slice($array,0,$predefinedNumber,true);

//the next entry determines whether we have ties
$next = array_slice($array,$predefinedNumber,1,true);

//active tie on entries with this value
$nextvalue = reset($next);

//the above 2 statements would be equivalent to (take your pick):
//$values = array_values($array);
//$nextvalue = $values[$predefinedNumber];


foreach($array as $key => $value){
   echo $key.' '.$value;
   if($value == $nextvalue){
     echo ' tie';
   } else if(isset($winners[$key])){
     echo ' winner';
   }
   echo '<br>';
}
于 2013-04-22T22:08:40.913 回答