Php Array Sort clothing sizes (XXS XS SML XL XXL) and numbers in a dynamic array

I have an array with something like this:

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

But I want to sort my array as:

  S - M - L - XL - XXL 

I know that I can do this with usort (), but I 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 use asort () for this; to sort these values.

Is there any function / way to do this?

+6
source share
4 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"); 
+10
source

You can also use the usort function in PHP and provide the actual comparison function. Something like that:

 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 eg XXL to 48 } else { // deal with comparing eg XXL to M as you would } } usort($my_array, "cmp"); 
+4
source

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

Example:

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

This may be useful: https://gist.github.com/adrianbadowski/5c2f287a96d10a115d75f02f12b9e134

Sorting an 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')

0
source

Source: https://habr.com/ru/post/898585/


All Articles