How to sort a foreach by an array value?

Asked

Viewed 920 times

0

Good afternoon guys, I’m doing a ranking with 10 people, is showing the 10, however I wanted to display in descending order through the value score

<article class="rank">
<h2>Ranking de Jogadores Online</h2>
<?php
    if(!is_array($aTotalPlayers) || count($aTotalPlayers) == 0){
    echo '<br /><i>No players online!</i>';
  } else {
  ?>
  <table class="table table-striped table-bordered" style="width:600px;" align="center">
    <tr>
        <td><b>#</b></td>
        <td><b>Nickname</b></td>
        <td><b>Score</b></td>
    </tr>
  <?php
    $i = 0;
    foreach($aTotalPlayers as $id => $value){
        if($i >= 10){
            break;
        }
        $i++;
  ?>
    <tr>
        <td><?php echo $i; ?></td>
        <td><?php echo htmlentities($value['Nickname']); ?></td>
        <td><?php echo $value['Score']; ?></td>
    </tr>
  <?php
    }
        echo '</table>';
    }

  ?>  

I mean, I’d have to show the 10 that have the most score in the descending order, you could help me?

1 answer

1

Two ways to solve the problem:

  1. in the SQL query, place at the end of your query order by Score DESC.
  2. order your array, picking the collection before the loop: asort() is decreasing, sort() is growing: asort($aTotalPlayers);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.