Sorting Sizes

Hi all, probably a quick one, how can I order my sizes in the correct order from youngest to oldest. I’m using the sort function but it’s sorting exactly how I’m wanting. Any help is appreciated as always :slight_smile:

The function 'usort’ sorts the array according to a user defined function. The 3rd parameter is a callback function. You should define it to split strings into from, to and units (e.g. from=0, to=3, units=months). A good function to split strings is "[URL=“http://www.php.net/manual/en/function.explode.php”]explode".

Hey dude, thanks for your reply. Could you give me a breif example of how this is done…I’m not quite following… :confused:

Yes, uksort takes two arguments a reference to an array and a function name, for example uksort($a, “cmp”);

So, the function “cmp” takes two arguments. We’ll define one that will compare 2 strings by splitting them into units (months < years), and ranges:
(3-6 > 0-3).
How to split them?
Take the units using the function explode, as follows:
$tmp=explode(’ ‘, $arg);
If arg=‘0-3 months’, Now $tmp[0]=‘0-3’, and $tmp[1]=‘months’
Now, we’ll split $tmp[0] to get the range:
$rng=explode(’-', $tmp[0]);
Now, $rng[0]=‘0’, and $rng[1]=‘3’.
$rng[0] is a number.

OK, you should apply this to both arguments.
The cmp($a, $b) should return an integer. That integer is:
negative if $a<$b
zero if $a==$b
positive if $a>$b


$array = array(
  '0-3 Months',
  '3-4 Years',
  '3-6 Months',
  '5-6 Years',
  '6-9 Months'
);

function weigh($a, $b){

  $a = sscanf($a, '%d-%d %s');
  $b = sscanf($b, '%d-%d %s');

  $map = array(
    'Years'   => 12,
    'Months'  => 1
  );

  $a = $a[1] * $map[$a[2]];
  $b = $b[1] * $map[$b[2]];
  
  if($a === $b){
    return 0;
  }

  return $a < $b ? -1 : 1 ;
}

usort($array, 'weigh');

print_r(
  $array
);

/*
  Array
  (
      [0] => 0-3 Months
      [1] => 3-6 Months
      [2] => 6-9 Months
      [3] => 3-4 Years
      [4] => 5-6 Years
  )
*/

Hey chaps, that has done the job beautifully. All working very well. Just need to try and get my head around how it all works (:

Why are you sorting at all?

I’m building an e-commerce site, think it’s eaiser to read if the sizes are in order. Not yet got to the Payment Gateway, dreading that. Unsure how tough it is to implement?