开发者

Sorting data by value (and using color) in php

开发者 https://www.devze.com 2023-03-19 11:49 出处:网络
I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their

I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their row blue. Any idea how I could do this?

file one:

<!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");
  开发者_如何学Go  ?>

    <?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>';
?>


Format all players/scores into arrays like array('name' => 'Bob', 'score' => 42):

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

Sort the array by score (PHP 5.3 syntax):

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

Output the results, setting a class on the first row:

$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']));
}

Now highlight that class using CSS (or do it directly in the HTML, or whatever else you want to do).

0

精彩评论

暂无评论...
验证码 换一张
取 消