2

I have mysql table i.e

id | a | b | c | d |ud_id
 1 | 20| 8 | 45| 18| 1

Now I want to retrieve that data in php sort the array and find the highest field in this example (c=45)

$query="SELECT `a`, `b`, `c`, `d` from table where ud_id=1";
$rs=mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($rs);

But how can I sort this associative array and find the highest key?

Cœur
  • 37,241
  • 25
  • 195
  • 267
souce code
  • 665
  • 3
  • 9
  • 18

2 Answers2

5

PHP has a whole bunch of sorting functions.

The one is sounds like you want is asort()

See the PHP manual for the other alternatives such as sort(), ksort(), natsort(), usort(), and a number of other variations. There's also shuffle() to sort randomly.

[EDIT] Okay, step-by-step to get the highest value out of the array:

asort($row);  //or arsort() for reverse order, if you prefer.
end($row);  //positions the array pointer to the last element.
print current($row); //prints "45" because it's the sorted highest value.
print key($row); //prints "c" because it's the key of the hightst sorted value.

There are a whole bunch of other ways to do it as well.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • when i used `print_r(sort($row));` this give me the result 1 and i want the hight key value like `['c']=>45` – souce code Mar 31 '11 at 09:31
  • @source: okay, so what if you try `asort()` as I suggested? – Spudley Mar 31 '11 at 09:33
  • okay i use `asort($row); print_r($row)` and the result is `Array ( [1] => 8 [b] => 8 [3] => 18 [d] => 18 [0] => 20 [a] => 20 [2] => 45 [c] => 45 )` then how can i get the highest value from this array. – souce code Mar 31 '11 at 09:40
  • @source: see my edits for one way to do it. But there's any number of other ways to do the same thing. – Spudley Mar 31 '11 at 09:50
2

Just like @Spudley said, arsort is the answer. You can get the first key of the resulting array by getting the first of its array_keys.

// ...
$row = mysql_fetch_assoc ($rs);
arsort ($row);
$keys = array_keys ($row);
printf ("key: %s, value: %s", $keys[0], $row[$keys[0]]);

Also note mysql_fetch_assoc.

vbence
  • 20,084
  • 9
  • 69
  • 118
  • but `asort` sort the array in ascending order and want to sort it in descending order so that on the first offset there should be the highest value. – souce code Mar 31 '11 at 09:47
  • @source - if you **read the manual** pages that I linked you to, you'll see that `asort()` has a matching function `arsort()` to do the same sort in reverse order. – Spudley Mar 31 '11 at 09:49
  • @Spudley my desired function was `arsort()` not `asort()` any way thank u v much – souce code Mar 31 '11 at 09:52