0

私は何百人ものユーザーを追跡し、彼らの経験をつかみ(それを保存し)、そして追跡のための指定された時間が終わったらオンデマンドでそれを再びつかむプログラムを作っています。私がやろうとしているのは、得られた経験の量を名前と関連付けながら並べ替え、得られた経験を最高から最低に出力することです。

これが私がしていることの例です:

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;
}

ですから、変数を出力する場合は、「a」が最初になるように作成しようとしています(ご覧のとおり、「a」が唯一の「人」であるためです。他の人よりも多くの経験')、そして'be'はアルファベット順にそれに従います。現在、データが収集される前にアルファベット順に並べ替えられているため、得られた経験を並べ替えるだけでよいと思います。

どうすればこれを達成できますか?

4

1 に答える 1

0

最も簡単な方法は、おそらく値を多次元配列に入れてから、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]);
  }
}
于 2011-08-11T07:08:07.437 に答える