Limit output after sorting an array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BaseballGraphs
    New Member
    • Sep 2010
    • 75

    #1

    Limit output after sorting an array?

    Hello,

    I am sorting my array so that the values go from high to low. My array contains about 1400 values in it, but I just want to show the top 50 results.

    How can I go about limiting my sorted array to just the top 50 overall values?

    If I add, 'LIMIT 50' to this $sql query:
    Code:
    $sql = sprintf('SELECT * FROM data WHERE day = CURdate()-INTERVAL 1 day AND statistic_id = %d', $statistic_id);
    it simply limits it to the first 50 entries. I would like to effectively limit it to the first 50 entries after I've performed the sort.

    Here is my code. Any advice would be very helpful!
    Code:
    <?
      $statistic_id = $_GET['s'];
      $pid = $_GET['p'];
      include 'index.php';
    
      $sql = sprintf('SELECT * FROM data WHERE day = CURdate()-INTERVAL 1 day AND statistic_id = %d', $statistic_id);
      $result = mysql_query( $sql );
      $array = array();
      while( $obj = mysql_fetch_object( $result ) )  {
      $array[ $obj->player_id ] = $obj->value;
      }
    
      function getNameFromId ( $player_id ) {
        $sql = sprintf( 'SELECT name FROM players WHERE id = %d', $player_id );
        $res = mysql_query( $sql );
        $arr = mysql_fetch_array( $res );
        return $arr[ 'name' ];
      }
    
      arsort( $array );
    
      $i = 0;
      foreach ( $array as $player_id => $value ) {
      $i++;
      $player_name = getNameFromId ( $player_id );
      echo sprintf( "\n%s is ranked %d with a value of %s <br/>", $player_name, $i, $value );
       }
    ?>
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    can you order the value already in SQL?

    Code:
    SELECT * FROM data WHERE day = CURdate()-INTERVAL 1 day AND statistic_id = %d', $statistic_id ORDER BY value DESC LIMIT 50

    Comment

    • BaseballGraphs
      New Member
      • Sep 2010
      • 75

      #3
      Great! That worked perfectly!

      Comment

      Working...