【问题标题】:php, sort an array from mysqlphp,从mysql中对数组进行排序
【发布时间】:2013-11-23 20:16:48
【问题描述】:

我正在对三列进行查询;一列包含文本,另外两列包含数字。我对这些数字进行了计算,得到了一个名为 $average 的新数字。然后我将结果吐出到一个 html 表中。表中的行按照它们从数据库中出来的顺序排序。我正在尝试对表格进行排序,以便数据从最高 $average 显示到最低(同时仍与第一列中的正确文本值正确关联)。

我尝试了一些 asortforeach 的东西,但我只成功地犯了一堆错误。

关于我如何解决这个问题的任何想法? 谢谢。

这是当前的游戏状态:

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

【问题讨论】:

  • 您可以对数据库中的数据进行排序——接收后无需排序。
  • 并使用您的查询进行计算。
  • 有什么原因不能在你的 SQL 查询中排序?
  • @马克贝克。唯一的原因是我自己的无知:D

标签: php mysql arrays sorting


【解决方案1】:

你可以

  • 让数据库进行排序(如其他海报所建议的那样)
  • 自己对数据进行排序(就像您尝试做的那样)
  • 让用户通过 JavaScript 函数对数据进行排序。我最喜欢的是 http://www.javascripttoolbox.com/lib/table/

【讨论】:

    【解决方案2】:

    将此作为您的查询

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

    【讨论】:

      【解决方案3】:

      您可以在查询中进行计算和排序:

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

      【讨论】:

      • 啊,我不知道事情可以这样做。工作得很好,而且更整洁。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多