I have the following code:
我有以下代码:
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>";
}
I have been able to create the array of the totals from the database records but need to sort the values in descending order.
我已经能够从数据库记录创建总数的数组,但是需要按降序对值进行排序。
For example, before sorting:
例如,在排序:
- 107
- 107年
- 563
- 563年
- 109
- 109年
- 246
- 246年
- 897
- 897年
and after sorting:
和后整理:
- 897
- 897年
- 563
- 563年
- 246
- 246年
- 109
- 109年
- 107
- 107年
1 个解决方案
#1
0
arsort maintains array keys, so if you begin with
arsort维护数组键,所以如果您开始时。
0 => 100
1 => 50
2 => 75
3 => 25
You will end up with
你最终会得到。
0 => 100
2 => 75
1 => 50
3 => 25
Which - on the surface - seems like what you want. The problem is that you're then looping through these and displaying them in the key order 0, 1, 2, 3 in your for($x = 0; $x < $k; $x++)
loop.
表面上看,这是你想要的。问题是,你要循环遍历这些并将它们显示在关键的0、1、2、3中($x = 0;$ x < $ k;$ x + +)循环。
One solution to this would be to use foreach
instead:
解决这个问题的一个办法是:
foreach ($tot as $number_to_display) {
echo $number_to_display . "<br>";
}
which will loop through them in the array order rather than iterating through keys sequentially as you tried.
这将在数组顺序中遍历它们,而不是按顺序遍历键。
The better solution, as has been commented, would be to use a sort condition in your SQL, something like:
正如所评论的那样,更好的解决方案是在SQL中使用排序条件,比如:
ORDER BY total DESC
#1
0
arsort maintains array keys, so if you begin with
arsort维护数组键,所以如果您开始时。
0 => 100
1 => 50
2 => 75
3 => 25
You will end up with
你最终会得到。
0 => 100
2 => 75
1 => 50
3 => 25
Which - on the surface - seems like what you want. The problem is that you're then looping through these and displaying them in the key order 0, 1, 2, 3 in your for($x = 0; $x < $k; $x++)
loop.
表面上看,这是你想要的。问题是,你要循环遍历这些并将它们显示在关键的0、1、2、3中($x = 0;$ x < $ k;$ x + +)循环。
One solution to this would be to use foreach
instead:
解决这个问题的一个办法是:
foreach ($tot as $number_to_display) {
echo $number_to_display . "<br>";
}
which will loop through them in the array order rather than iterating through keys sequentially as you tried.
这将在数组顺序中遍历它们,而不是按顺序遍历键。
The better solution, as has been commented, would be to use a sort condition in your SQL, something like:
正如所评论的那样,更好的解决方案是在SQL中使用排序条件,比如:
ORDER BY total DESC