0

I'm querying a table in a db using php. one of the fields is a column called "rank" and has data like the following:

none
1-bronze
2-silver
3-gold
...
10-ambassador
11-president

I want to be able to sort the results based on that "rank" column. any results where the field is "none" get excluded, so those don't factor in. As you can already guess, right now the results are coming back like this:

1-bronze
10-ambassador
11-president
2-silver
3-gold

Of course, I would like for it to be sorted so it is like the following:

1-bronze
2-silver
3-gold
...
10-ambassador
11-president

Right now the query is being returned as an object. I've tried different sort options like natsort, sort, array_multisort but haven't got it to work the way I'm sure it can. I would prefer keeping the results in an object form if possible. I'm passing the data on to a view in the next step. although, it's perfectly acceptable to pass the object to the view and then do the work there. so it's not an issue after all. :)

thank you for your help. i'm hoping I'm making sense.

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
Jason Shultz
  • 940
  • 1
  • 19
  • 36

3 Answers3

0

Get the values in an array an sort it in PHP using natsort()

Natsort

Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36
0

How about using this function to sort. I assume if you are getting an object you should convert object to array then use this

function arraySubSort($array, $subkey, $sort = 'asort') 
{
  foreach($array as $key => $value) 
  {
    $temp[$key] = strtolower($value[$subkey]);
  }

  $sort($temp);
  foreach($temp as $key => $value) 
  {
    $result[] = $array[$key];
  }
  return $result;
}

$data = $your_array;
$field = 'ranks';
arraySubSort($data,$field);

It will sort the array with the field you assign. If you are getting multiple records its a good thing to use to sort.

Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
0

This will work -

SELECT alphanumeric, integer FROM sorting_test ORDER BY LENGTH(alphanumeric), alphanumeric

source - Natural Sort in MySQL

Community
  • 1
  • 1
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37