【问题标题】:Creating two dimensional array from mysql records in php从php中的mysql记录创建二维数组
【发布时间】:2017-01-07 07:52:56
【问题描述】:

我有以下代码:

while($row12 = mysql_fetch_array($result12)) {
    $position = $row12['position'];
    $tot[$k] = $row12['total'];
    $k++;
}

$arr = arsort($tot);

for($x = 0; $x < $k; $x++) {
    echo $tot[$x]."<br>";
}

我已经能够根据数据库记录创建总计数组,但需要按降序对值进行排序。

例如排序前:

  • 107
  • 563
  • 109
  • 246
  • 897

排序后:

  • 897
  • 563
  • 246
  • 109
  • 107

【问题讨论】:

  • 您可以对 sql 查询中的值进行排序。我认为这比在 php 中要快得多。 php.net/manual/en/array.sorting.php 在这里你可以阅读关于使用 php 函数进行排序...所以你不必实现自己的排序函数
  • 我知道这一点,但它无法解决问题,因为我尝试过
  • 去掉烂英文,清晰显示输入输出再码累
  • 代码格式只在内容的开头起作用

标签: php mysql arrays sorting indexed


【解决方案1】:

arsort 维护数组键,所以如果你从

0 => 100
1 => 50
2 => 75
3 => 25

你最终会得到

0 => 100
2 => 75
1 => 50
3 => 25

这 - 从表面上看 - 似乎是你想要的。问题是您随后会遍历这些并在for($x = 0; $x &lt; $k; $x++) 循环中以键顺序 0、1、2、3 显示它们。

对此的一种解决方案是改用foreach

foreach ($tot as $number_to_display) {
    echo $number_to_display . "<br>";
}

它将按数组顺序循环遍历它们,而不是像您尝试的那样按顺序遍历键。

如前所述,更好的解决方案是在 SQL 中使用排序条件,例如:

ORDER BY total DESC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2019-12-04
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多