1

カテゴリごとに可変数の勝者を持つ選挙を実行しました。(1 つのカテゴリに 3 人の勝者、別の 1 つの勝者、別の 2 つの勝者など)

現在、次のような結果を表示しています。

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

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

これは戻ります

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

私がする必要があるのは、2 つの値がその所定の数値に基づいて同じである場合に何かをエコーすることです。したがって、所定の数が 1 の場合、次のようになります。

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

所定の数が 2 の場合、2 番目と 3 番目の値が同じではないため、次のようになります。

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

お時間をいただきありがとうございます。

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 に答える