PHP排名功能与TIES

时间:2014-06-04 22:39:31

标签: php html

所以我有一个函数,它接受一个数字并将其作为一个位置输出。如何使功能考虑到关系。我有一个排名数据库,这个PHP代码回应表上的排名。现在它排名但不考虑关系。我该怎么做呢

<?php

function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
  switch ($num % 10) {
    // Handle 1st, 2nd, 3rd
    case 1:  return $num.'st';
    case 2:  return $num.'nd';
    case 3:  return $num.'rd';
  }
}
return $num.'th';
  }

?>


<?php

$link = mysqli_connect("localhost", "citricide", "321213123Lol", "juneausmashbros");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * FROM rankings ORDER BY points DESC";
$result = mysqli_query($link, $query);

echo '<article class="content grid_6 push_3">';
echo '<h1>';
echo 'Project M Summer Ranbat Rankings';
echo '</h1>';
echo '<section>';
echo '<center>';
echo '<table style="width:400px" class="rankslist">';
echo '<tr>';
echo  '<th width="15%"><b>Rank</b></th>';
echo '<th width="45%"><b>Name</b></th>';
echo '<th width="45%"><b>Alias</b></th>';
echo  '<th width="15%"><b>Points</b></th>';
echo '</tr>';
$ass = 0;
while($row =  $result->fetch_array()) {
    $ass++;
    echo '<tr>';
    if ($ass == 1) {
        echo ' <center><td><B><font color=#FFD700>';
    } else if ($ass == 2) {
        echo ' <center><td><B><font color=#CCCCCC>';
    } else if ($ass == 3) {
        echo ' <center><td><B><font color=#cd7f32>';
    } else {
        echo '<td>';
    }
    echo addOrdinalNumberSuffix($ass);
    echo ' </font></B</td></center>';
    echo ' <td>'.$row['name'].'</td>';
    echo  '<td>'.$row['alias'].'</td>' ;
    echo  '<td>'.$row['points'].'</td>';
    echo '</tr>';
}
echo '</table>';
echo '</center>';
echo '</section>';
echo '</article>';
?>     

1 个答案:

答案 0 :(得分:0)

您似乎需要其他变量来跟踪排名和之前的值。通过这样做,你可以处理关系。

例如:

$ass = 0; // current record count
$rank = 0; // rank
$last_points = NULL; // variable to store last ranked value
while($row =  $result->fetch_array()) {
    $ass++;
    // check if value changes and reset rank if it does
    if ($row['points'] !== $last_points) {
        $rank = $ass;
        $last_points = $row['points'];
    }
    echo '<tr>';
    if ($rank == 1) {
        echo ' <center><td><B><font color=#FFD700>';
    } else if ($rank == 2) {
        echo ' <center><td><B><font color=#CCCCCC>';
    } else if ($rank == 3) {
        echo ' <center><td><B><font color=#cd7f32>';
    } else {
        echo '<td>';
    }
    echo addOrdinalNumberSuffix($rank);
    echo ' </font></B</td></center>';
    echo ' <td>'.$row['name'].'</td>';
    echo  '<td>'.$row['alias'].'</td>' ;
    echo  '<td>'.$row['points'].'</td>';
    echo '</tr>';
}

所以说你的观点是这样的:

100
100
90
80

$rank值为:

1
1
3
4