开发者

PHP Condition within a loop - PHP

开发者 https://www.devze.com 2023-03-10 13:58 出处:网络
I have an array like this: $team_scores = array(\'Tigers\' => 3, \'Spikes\' => 6, \'Crashers\' => 8, \'Fortress\' => 2);

I have an array like this:

$team_scores = array('Tigers' => 3, 'Spikes' => 6, 'Crashers' => 8, 'Fortress' => 2);

created from a MySQL query in which names are from one column and values are from another column. I want to create a page for each team that should indicate the name of the team and its score as well as position. So in this example I would have 4 pages and each page shows the name and score for a team without showing any information about 开发者_Python百科other teams other than the total teams that participated. So it would show

Name: Spikes Score: 6 Position: 2/4,

For Crashers it would be

Name: Fortress Score: 2 Position: 4/4,

I am thinking a foreach loop would do but am only able to echo the teams and scores on a single page, when what I need is to create 4 pages, one for each item in the array. I am able to do that with data just being pulled from the database, but from such data I do not think its possible to determine the position of each team without having the data in one array.

Is that even possible or am I asking PHP to do what cannot be done? Any help will be deeply appreciated.


Don't do it in PHP. You want to use something like an ORDER BY clause in your SQL query to sort your results by score. You can then use a LIMIT on the query to only fetch one row at a time, and combine that with an offset to get exactly the row you need.


In MySQL you'd do:

SELECT 
   @position:= @position + 1 AS position,
   score_table.*
FROM 
   score_table,
   (SELECT @position := 0) p 
ORDER BY score;

Then you could do:

$count = count($results);
foreach ($results as $result) {
    echo "Name: {$result['name']}";
    echo "Score: {$result['score']}";
    echo "Position: {$result['position']}/{$count}";
}

If you want to do it in plain SQL (e.g.: compatible with other SQL databases), you'd do:

SELECT 
   *
FROM 
   score_table
ORDER BY score;

Then, considering you have numerically indexed $results:

foreach ($results as $key => $result) {
    echo 'Position: '.($key+1);
}


Use $_GET to figure out which team to display:

/teams.php?team=spikes
...
$i = 0;
$nbTeams = count($team_scores)
foreach ($team_scores as $team => $score)
{
   $i++;
   if ($team == $_GET[team])
   {
       echo "Name: $team Score:  $score Position: $i/$nbTeams";
   }
}
0

精彩评论

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