7

I've a array with something like that:

Array ( [0] => XL [1] => M [2] => L [3] => XL [4] => S [5] => XXL)

But i want to sort my array like:

 S - M - L - XL - XXL

I know that i can do it with usort() but, i've get some other values like numbers:

Array ( [0] => 14 [1] => 37 [2] => 38 [3] => 39 [4] => 40 [5] => 44 [6] => 36 [7] => 28 )

I mean this is a dynamic array...

I'm using for that asort(); for sorting that values.

Is there any function/way to do that?

1
  • Why do you have these wildly different sets of values in the same array? Or why do you have to use the same function to sort both arrays if they're different arrays?
    – MatsLindh
    Commented Oct 4, 2011 at 12:41

4 Answers 4

17
function cmp($a, $b)
{

$sizes = array(
"XXS" => 0,
"XS" => 1,
"S" => 2,
"M" => 3,
"L" => 4,
"XL" => 5,
"XXL" => 6
);

$asize = $sizes[$a];
$bsize = $sizes[$b];

if ($asize == $bsize) {
    return 0;
}

return ($asize > $bsize) ? 1 : -1;
}

usort($your_array, "cmp");
1
  • 1
    Great, I love that. Just a small addition, usort sorts by array values, you can use the same function with uksort to sorty by array keys. Commented Apr 1, 2016 at 15:58
4

You can use still use usort function in PHP and supply the actual comparison function. Something like this:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }

    if(is_numeric($a) && is_numeric($b))
    {
        $a = intval($a);
        $b = intval($b);
        return $a > $b ? 1 : -1;
    }
    elseif(is_numeric($a) || is_numeric($b))
    {
        // somehow deal with comparing e.g. XXL to 48
    }
    else
    {
        // deal with comparing e.g. XXL to M as you would
    }
}

usort($my_array, "cmp");
1
  • @dr.linux I know you didn't - somebody else did, I'm just interested to know why
    – Aleks G
    Commented Oct 5, 2011 at 8:16
1

well you can arrange the keys with the corresponding size, you have S,M,L (-1,1,1) if you have X`s in front just generate a value, make the resulting value the key (maybe you ought to round() ) and voila

EX:

    S=15
    X=1
    XXS = 15-2*1 =13
    XS= 15-1=14
array([13]=>'XXS',[14]=>'XS');
0

This can be helpful: https://gist.github.com/adrianbadowski/5c2f287a96d10a115d75f02f12b9e134

Sort array of sizes: array('1', '5', '1XL', '4', '10.5', '9.5', 's', 'XS', 'L', 'm') into: array('1', '4', 5', '9.5', '10.5', 'XS', 's', 'L', '1XL')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.