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

10,885

Solution 1

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");

Solution 2

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');
Share:
10,885
dr.linux
Author by

dr.linux

Hello World! I'm H.İbrahim Yılmaz (a.k.a. drlinux), co-author of Laravel Application Development Blueprints and Laravel Design Patterns and Best Practices books. I am a Python and PHP developer, Erlang newbie and e-commerce consultant. I've worked as a developer and software coordinator in over a dozen ventures including e-commerce, news and online media services. I have experience with as Google, YouTube, Facebook, Twitter, Grooveshark, and Paypal API. I'm learning French, Erlang and bass guitar. When I'm not working on client projects, I am often coding or playing my guitar. I live in a house full of Linux boxes in Turkey. Requests for my résumé are welcome. Please feel free to get in touch with me via my personal home page : http://drlinux.org

Updated on June 05, 2022

Comments

  • dr.linux
    dr.linux almost 2 years

    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?

  • Florian Rachor
    Florian Rachor about 8 years
    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.