在PHP中按值(和使用颜色)排序数据

时间:2011-07-11 02:24:00

标签: php forms sorting

我有一个图表和一个正在接收一些数据的文本文件。我想通过将具有最高分的用户放在桌面顶部并将其中的所有内容着色为蓝色来组织我拥有的数据。知道我怎么能这样做吗?

文件一:

<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>High Score</title>
</head>
<body>
form action="data.php" method="POST">
    <table border="1">
    <tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
    <tr><td>Score</td><td><input type="text" name="score"</td></tr>
    <tr><td colspan="2" align="center"><input type="submit"></td></tr>
    </table>
</form>
</body>
</html>

Data.php:

<?php
$name = $_POST['name'];
$score = $_POST['score'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];

@ $fp = fopen("$DOC_ROOT/../phpdata/highscore.txt","ab");

    if(!$fp) {
    echo 'Error: Cannot open file.';
    exit;
    }

    fwrite($fp, $name."|".$score."\n");
    ?>

    <?php
    $DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
    $players = file("$DOC_ROOT/../phpdata/highscore.txt");

    echo "<table border='2'>";
    echo "<tr> <td>Name</td>  <td>Score</td> </tr>";
    for($i = 0; $i < sizeof($players); $i++) {
    list($name,$score) = explode('|', $players[$i]);
    echo '<tr><td>'.$name.'</td><td>'.$score.'</td></tr>';
    }
    echo '</table>';
?>

1 个答案:

答案 0 :(得分:1)

将所有玩家/分数格式化为array('name' => 'Bob', 'score' => 42)等数组:

foreach ($players as &$player) {
    list($name, $score) = explode('|', $player);
    $player = compact('name', 'score');
}
unset($player);

按分数排序数组(PHP 5.3语法):

usort($players, function ($a, $b) { return $b['score'] - $a['score']; });

输出结果,在第一行设置一个类:

$first = true;
foreach ($players as $player) {
    $class = $first ? ' class="highlight"' : null;
    $first = false;
    printf('<tr%s><td>%s</td><td>%s</td></tr>', $class, htmlspecialchars($player['name']), htmlspecialchars($player['score']));
}

现在使用CSS突出显示该类(或直接在HTML中执行,或者您想要执行的任何其他操作)。