php, sort an array from mysql

谁都会走 提交于 2020-01-16 19:38:33

问题


I'm running a query on three columns; one column contains text, the other two contain numbers. I do a calculation on these numbers to get a new number called $average. I then spit out the result to an html table. The rows in the table are sorted in the order they come out of the database. I'm trying to sort the table so that the data is displayed from highest $average to lowest (while still be correctly associated with the correct text value from the first column).

I've tried some asort and foreach stuff, but I've only succeeded in making a mess of errors.

Any ideas as how I go about this? Thanks.

This is the current state of play:

/ db query
  if (!$result = mysqli_query($link,"SELECT quiz_name, 
                                            quiz_attempts, 
                                            cumulative_score 
                                       FROM scoredata")) {
  echo("There was a problem: " . mysqli_error($link));
  exit();
  }
...
// got results?
  if(mysqli_num_rows($result) >= 1) {

  $output = "";
  $output .= "<table>\n";
  $output .= "<tr><th>Quiz name</th> <th>Played</th> <th>Avg. score</th></tr>\n";

  while($row = mysqli_fetch_array($result)) {

    $output .= "<tr><td>".str_replace('_', ' ', $row['quiz_name']) . "</td>";
    $output .= "<td>" . $row['quiz_attempts'] . "</td>";

    // calculate average score
    $average = $row['cumulative_score']/$row['quiz_attempts'];

    $output .= "<td>" . round($average,2) . "</td></tr>";
   }

  $output .= "</table>\n";
  echo $output;
}
...

回答1:


You can do calculation and sorting in your query:

SELECT 
    quiz_name, 
    quiz_attempts, 
    cumulative_score,
    (cumulative_score/quiz_attempts) as score_avg
FROM scoredata
ORDER BY score_avg DESC



回答2:


You can

  • let the db do the sorting (as suggested by other posters)
  • sort the data yourself (as you are trying to do)
  • let the user sort the data via JavaScript functions. My favourite is http://www.javascripttoolbox.com/lib/table/



回答3:


Make this your query

    SELECT quiz_name, 
           quiz_attempts, 
           cumulative_score,
           cumulative_score / quiz_attempts as avg_score
    FROM scoredata
    ORDER BY avg_score


来源:https://stackoverflow.com/questions/19916353/php-sort-an-array-from-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!