SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    stirling
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Php array problem

    Hi, I have a really annoying problem with an array that I just cant seem to figure out. Can anyone help me out?

    I read in several rows of values from my sql database. I want to place them in a table, but first I work out a new value based on some of the db values, so I can not sort in the sql statement. I want to sort the rows of the table based on this newly calculated value.

    How do I create the array to hold the values firstly? The values each row should have are ($row[1], $score, $row[7]) where score is the newly calculated value.
    Then how do I sort this array on the new value of $score? So that all the related values, $row[1], $row[7] are sorted aswell?

    Any ideas??

    Thanks.

  2. #2
    SitePoint Enthusiast
    Join Date
    Mar 2005
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    use an associative array

    Use an associative array, where the keys are the scores, the values are arrays of your data, like
    PHP Code:
    while( $row mysql_fetch_row() ) {
      
    $score = ;//calc score
      
    $newarray[$score] = array( values to save in array) ;
    }
    ksort($newarray);
    foreach( 
    $newarray as $key => $vals ) {
      print 
    "$key: ";
      print 
    join(", ",$vals;


  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And what if two or more records have the same score?

    davidhardie

    You can use array_multisort or usort, or, better, try to calculcate "score" directly in your query, not in php.

  4. #4
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    stirling
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks now I have the values in the array as I want them.
    Array([0] = Array([score] => 2 [hole] => 18 [player] => fred) [1] => Array([score] => -4 [hole] => 16 [player] => david)[2] => Array(....

    I tried the array multisort,

    array_multisort($score, SORT_ASC, $hole, SORT_DESC, $player, SORT_ASC, $data);

    But it didnt change the order of the array when I print out the array. Does this sort seem OK? Dont see why it didnt change.

    Thanks, David.

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    stirling
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorted it! simply replaced the multisort with sort($data); and it worked perfectly. Amazing.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •