Skip to content

Instantly share code, notes, and snippets.

@cyberdev
Created May 1, 2024 15:21
Show Gist options
  • Save cyberdev/a0ad4a997aa94b742daed9619dec9f1c to your computer and use it in GitHub Desktop.
Save cyberdev/a0ad4a997aa94b742daed9619dec9f1c to your computer and use it in GitHub Desktop.
Sorting Class
<?php
class sorter {
private $_array = array();
function __construct($array) {
$this->_array = $array;
}
public function do_sort_size(){
usort ($this->_array, array('sorter','sort_size'));
return $this->_array;
}
public function do_sort_numeric(){
usort ($this->_array, array('sorter','sort_numeric'));
return $this->_array;
}
public function do_sort_text(){
usort ($this->_array, array('sorter','sort_text'));
return $this->_array;
}
/* public function elaborate() {
if (preg_match("~([0-9]+|[0-9])~", $this->_array[0])) {
usort ($this->_array, array('sorter','sort_numeric'));
}
else {
if (preg_match("~(?=^(X)(?=(L)$))|(?=^(L)$)|(?=^(M)$)~", $this->_array[0])) {
usort ($this->_array, array('sorter','sort_size'));
}
else {
usort ($this->_array, array('sorter','sort_text'));
}
}
return $this->_array;
} */
protected static function sort_numeric($a, $b) {
return $a - $b;
}
protected static function sort_size($a, $b) {
static $sizes = array('2XS', 'XS', 'S', 'M', 'L', 'XL', '2XL');
$asize = 100;
$apos = -1;
$bsize = 100;
$bpos = -1;
foreach ($sizes AS $val => $str) {
if (($pos = strpos($a, $str)) !== FALSE && ($apos < 0 || $pos < $apos)) {
$asize = $val;
$apos = $pos;
}
if (($pos = strpos($b, $str)) !== FALSE && ($bpos < 0 || $pos < $bpos)) {
$bsize = $val;
$bpos = $pos;
}
}
return ($asize == $bsize ? 0 : ($asize > $bsize ? 1 : -1));
}
protected static function sort_text($a, $b) {
static $sizes = array("extra small","small","quite small?","something a bit too small","you surely don't fit there.","medium","big","very big","huge","enormous!");
$asize = 100;
$apos = -1;
$bsize = 100;
$bpos = -1;
foreach ($sizes AS $val => $str) {
if (($pos = strpos($a, $str)) !== FALSE && ($apos < 0 || $pos < $apos)) {
$asize = $val;
$apos = $pos;
}
if (($pos = strpos($b, $str)) !== FALSE && ($bpos < 0 || $pos < $bpos)) {
$bsize = $val;
$bpos = $pos;
}
}
return ($asize == $bsize ? 0 : ($asize > $bsize ? 1 : -1));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment