开发者

Sorting an array with hundreds of different names and values

开发者 https://www.devze.com 2023-03-27 13:20 出处:网络
I\'m making a program that tracks hundreds of users, grabs their experience (stores it), and then grabs it again on demand once the designated time for tracking is over.What I\'m trying to do is sort

I'm making a program that tracks hundreds of users, grabs their experience (stores it), and then grabs it again on demand once the designated time for tracking is over. What I'm trying to do is sort the amount of gained experience, while keeping it in association with the name, and then outputting the experience gained from highest to lowest.

Here's开发者_运维知识库 an example of what I'm doing:

display();

function display() {
    $participants = array("a", "b", "c", "d", "e");
    sort($participants);
    for ($i = 0; $i < count($participants); $i++) {
        $starting = getStarting($participants[$i]);
        $ending = getEnding($participants[$i]);
        $gained = $ending - $starting;
    }
}

function getStarting($name) {
    $a = "a";
    return $name == $a ? 304 : 4;
}

function getEnding($name) {
    $a = "a";
    return $name == $a ? 23 : 34;
}

So, I'm trying to make it so that if I were to print a variable, then 'a' would be first (because, as you can see, I made it so 'a' is the only 'person' that has gained more experience than the others'), then 'b-e' would follow it, alphabetically. It currently sorts it alphabetically before any data is collected, so I'm assuming all I'll have to do is sort the gained experience.

How could I achieve this?


The easiest way would probably be to put the values into a multidimensional array, then use usort():

function score_sort($a,$b) {
  // This function compares $a and $b
  // $a[0] is participant name
  // $a[1] is participant score
  if($a[1] == $b[1]) {
    return strcmp($a[0],$b[0]);  // Sort by name if scores are equal
  } else {
    return $a[1] < $b[1] ? -1 : 1;  // Sort by score
  }
}

function display() {
  $participants = array("a", "b", "c", "d", "e");

  // Create an empty array to store results
  $participant_scores = array();  

  for ($i = 0; $i < count($participants); $i++) {
    $starting = getStarting($participants[$i]);
    $ending = getEnding($participants[$i]);
    $gained = $ending - $starting;
    // Push the participant and score to the array 
    $participant_scores[] = array($participants[$i], $gained);
  }

  // Sort the array
  usort($participant_scores, 'score_sort');

  // Display the results
  foreach($participant_scores as $each_score) {
    sprintf("Participant %s has score %i\n", $each_score[0], $each_score[1]);
  }
}
0

精彩评论

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