-
-
Save iksecreeet/3dcdaa34ec05b5727669739efd5373a0 to your computer and use it in GitHub Desktop.
Sort various (clothing) sizes in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ObjectSize { | |
protected static $sizes = [ | |
'xxxxl', | |
'xxxl', | |
'xxl', | |
'xl', | |
'l', | |
'm', | |
's', | |
'xs', | |
'xxs', | |
'xxxs' | |
]; | |
public static function classify($value=null) | |
{ | |
$value = mb_strtolower(trim($value)); | |
// handle ranges | |
if (mb_strpos($value, '-')) { | |
$values = explode('-', $value); | |
$part1 = self::classify($values[0]); | |
if ($part1) { | |
$part2 = self::classify($values[1]); | |
return $part1 - ($part2 / 100); | |
} | |
return false; | |
} | |
// handle clothing sizes | |
if ($clothingSizeIndex = array_search($value, ObjectSize::$sizes)) { | |
return $clothingSizeIndex * -1; | |
} | |
return false; | |
} | |
public static function compare($a, $b) | |
{ | |
$classA = self::classify($a); | |
$classB = self::classify($b); | |
if ($classA && $classB) { | |
if ($classA == $classB) return 0; | |
return $classA > $classB ? 1 : -1; | |
} | |
return strnatcmp($a, $b); | |
} | |
public static function sort(array $arr) | |
{ | |
usort($arr, 'self::compare'); | |
return $arr; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'ObjectSize.php'; | |
$sizes = [ | |
'XL', | |
1, | |
5, | |
6, | |
'L', | |
4.5, | |
'3.33', | |
'3,25', | |
'XXL', | |
'L-XXL', | |
'L-XXXL', | |
'a', | |
'ba', | |
'aaaa', | |
'S', | |
'5-50', | |
'5/6', | |
'50x80cm', | |
'L-XL', | |
'M', | |
10, | |
'104-15', | |
'A/75', | |
1, | |
'A/70', | |
'ab', | |
'XS', | |
'XXS' | |
]; | |
?> | |
<h1>Original sizes</h1> | |
<pre><?= print_r($sizes); ?></pre> | |
<h1>Classified sizes</h1> | |
<pre><?= print_r(array_map('ObjectSize::classify', $sizes)); ?></pre> | |
<h1>Sorted sizes</h1> | |
<pre><?= print_r(ObjectSize::sort($sizes)); ?></pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment