Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Array Sorting Clothing Sizes (XXS XS S M L XL XXL) and Numbers on a Dynamic Array

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?

like image 796
dr.linux Avatar asked Oct 04 '11 12:10

dr.linux


2 Answers

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");
like image 110
Adam Moss Avatar answered Oct 01 '22 20:10

Adam Moss


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");
like image 29
Aleks G Avatar answered Oct 01 '22 20:10

Aleks G