-1

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
  • 563
  • 109
  • 246
  • 897

and after sorting:

  • 897
  • 563
  • 246
  • 109
  • 107
moopet
  • 6,014
  • 1
  • 29
  • 36
Teejaygenius
  • 49
  • 1
  • 1
  • 6
  • 5
    you can sort the values in your sql query .. I think thats much faster then in php. http://php.net/manual/en/array.sorting.php here you can read about sorting with php functuons... So you do not have to implement youreown sorting function – Simon Müller Aug 30 '16 at 21:43
  • i knew about this but it cannot give a solution to the problem as i av tried it – Teejaygenius Aug 30 '16 at 22:09
  • remove bad English, clearly show input-output and then code tired – Barry Aug 31 '16 at 08:01
  • code formatting only worked at the start of the content – Barry Aug 31 '16 at 08:04

1 Answers1

0

arsort maintains array keys, so if you begin with

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.

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:

ORDER BY total DESC
moopet
  • 6,014
  • 1
  • 29
  • 36