Skip to content

Instantly share code, notes, and snippets.

@mathiasschopmans
Created December 4, 2016 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mathiasschopmans/e97ec92217353bdc9ac766214e0b0f0f to your computer and use it in GitHub Desktop.
Save mathiasschopmans/e97ec92217353bdc9ac766214e0b0f0f to your computer and use it in GitHub Desktop.
Sort various (clothing) sizes in an array
<?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;
}
}
<?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